【问题标题】:Update the Parent Scope from Child Directive从子指令更新父范围
【发布时间】:2015-09-16 23:42:21
【问题描述】:

就在我认为我已经掌握了 AngularJS 的时候,它把我抛到了一边。我正在尝试通过将父范围中的值传递到隔离范围来更新它,然后在那里进行更新。

我认为使用两种方式的数据绑定会很简单,如下所示:

在父控制器中:

var self = this;
self.variable = 'Init';

在元素中:

<div data-example-directive data-variable="ParentCtrl.variable"></div>

在子指令中:

scope: {
    variable: '='
}
link: function(scope) {

    scope.updateVal = function(updatedVal) {
        scope.variable = updatedVal;
    }
}
template: '<button ng-click="updateVal('Updated Value')"></button>'

现在,如果在该函数内部,我在scope.variable 上调用console.log,它会显示updatedVal 的正确值。但是在页面本身上,父级尚未更新。我需要调用某种“刷新”吗?

我认为 AngularJS 的重点是内置双向数据绑定,我不必要求它根据以后的逻辑更新值?一位同事使用了broadcast,但没有更优雅的解决方案吗?

【问题讨论】:

    标签: angularjs angularjs-scope angular-directive


    【解决方案1】:

    controllerAs 风格和$scope 风格你已经完成了一半,你需要选择一个。由于另一个答案显示前者,我会做后者(我更熟悉这个;p)

    angular.module('test', [])
    
    .directive('exampleDirective', function() {
      return {
        scope: {
          variable: '='
        },
        link: function(scope) {
          scope.updateVal = function(updatedVal) {
            scope.variable = updatedVal;
          }
        },
        template: '<button ng-click="updateVal(\'Updated Value\')">Update</button>'
      }
    })
    
    .controller('Test', function($scope) {
      $scope.variable = "Init";
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app='test' ng-controller="Test">
      {{variable}}
      <div data-example-directive data-variable="variable"></div>
    </body>

    【讨论】:

    • 抱歉。我从我当前的代码库中提取了它,却忘记将它添加到其中。让我仔细检查一下我的代码,然后回复你,我敢肯定,这就是我目前所拥有的。
    【解决方案2】:

    你的问题很简单:

    当您阅读时:在您的范围内您没有variable,因此 Angular 会尝试在父级中查找,等等...直到找到它。

    当您编写时:它将在您当前的范围内设置variable。但是你的父作用域仍然有旧的variable,你没有更新它,因为variable 并不直接在你当前的作用域中。

    看看:https://stackoverflow.com/a/16929117/3292234

    您可以使用 点符号 解决这个问题。 controller as 语法示例:

    <div ng-controller="controller1 as controller1">
        {{controller1.variable}}
        <div ng-controller="controller2 as controller2">
            <input ng-model="controller1.variable" type="text"/>
        </div>
    </div>
    

    【讨论】:

    • 是的,我之前的回答和你的回答一样,但我试图不直接引用控制器等。我明白这是尽量保持模块化的最佳做法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多