【问题标题】:angular directive variable not available in parent scope角度指令变量在父范围内不可用
【发布时间】:2015-12-10 11:27:06
【问题描述】:

我目前被困在一个简单的问题上:

我有一个controller.js

app.controller('WizardCtrl', function ($scope) {
  $scope.send = function() {
    console.log($scope.isPasswordChanged)
  }
});

我的观点.html

isPasswordChanged: {{ isPasswordChanged }} <br>
<update-password-field is-changed="isPasswordChanged"></update-password-field>
<button ng-click="send()"></button>

我的指令.js

app.directive('updatePasswordField', function () {
  return {
    restrict: 'E',
    scope: {
      isChanged: "="
    },
    templateUrl: "password-field-directive.html",
    link: function (scope) {
        // some magic to set isChanged value to true of false 
    }
  }
});

所以在我的 view.html 中,我可以看到“isPasswordChanged”的变化,它以某种方式在我的 $scope 中,但是如果我 console.log($scope) 则“isPasswordChanged”不存在。

为什么以及如何让它呈现?

【问题讨论】:

  • 你把console.log($scope) 放在哪里了?
  • 什么时候调用send函数?你能提供工作样本吗?
  • @K.Toress 在我的 send() 函数中,我更新了我的 view.html
  • @Grundy 我更新了我的 view.html
  • 我认为@Craig 有答案

标签: javascript angularjs


【解决方案1】:

我认为您需要在控制器的 function() 中包含 $scope。换句话说:

app.controller('WizardCtrl', ['$scope', function ($scope) {

否则我不相信它会起作用。

【讨论】:

  • 我认为应该是app.controller('WizardCtrl', function ($scope) {.. ?不是吗?
  • @K.Toress 好的,我已经修好了。
  • @Craig 关于这个主题,我可以在我的指令stackoverflow.com/questions/19311102/… 中注入 $scope
  • @Craig 抱歉,这只是一个示例,但我的真实代码在我的控制器中包含 $scope。我刚刚更新了代码。
【解决方案2】:

原来这可能是我的结构有问题。

我变了

is-confirmed="isPasswordConfirmed"

is-confirmed="ui.isPasswordConfirmed"

“ui”是我在 $scope 中定义的一个空对象。

及其工作。我尝试了一个独立的例子

http://plnkr.co/edit/bkMZTEWgkrmVfxqiYCcB?p=preview

但它在没有这些变化的情况下工作,它也可能与角度版本不匹配。

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多