AngularJs:为什么异步数据到达时我的指令内的范围不更新?

标签 angularjs angularjs-directive angularjs-scope

我有一个带有隔离范围的指令,它通过引用获取一个范围变量

angular.module('myApp')
    .directive('myDirective', function() {
        return {
            scope: {
                items: '='
            },
            templateUrl: 'template.html',
            replace: true,
            controller: 'myDirectiveCtrl',
            controllerAs: 'ctrl'
        };
    })
    .controller('myDirectiveCtrl', function($scope) {
        this.items = $scope.items;
    });

这是这样传递的:
    <div my-directive items='items'></div>

在外部 Controller 中,数据被异步加载,并且传递给指令的范围项被更新:
angular.module('myApp', [])
  .controller('myCtrl', function($scope) {

    $scope.setItems = function() {
      $scope.items = [
        'Here',
        'There',
        'Everywhere'
      ];
    };
  });

加载数据时,我的指令之外的范围会更新,但内部不会

我的html:
      <div my-directive items='items'></div> <!-- this doesn't update --> 

      Outside directive
      <ul ng-repeat='i in items'>            <!-- this does update -->
        <li>{{i}}</lu>
      </ul>

      <button ng-click="setItems()">Set items</button>

如何在我的指令中获取我的范围以进行更新?难道我

Plunker here

最佳答案

当 Angular 第一次运行你的指令的 Controller 函数时,你的 $scope.items === undefined , 所以当你做 this.items = $scope.items , 你的 this.items === undefined也。

就是这样。之后没有任何变化this.items .

这与 $scope.items 不同。 . $scope.items是双向绑定(bind)到外部范围的,因此每当 Angular 检测到外部更改时,它都会设置隔离范围变量。

最简单的方法(在我看来也是最合适的)是使用 $scope直接在指令中的属性:

<div>
    Inside directive
    <ul ng-repeat="i in items">
      <li>{{ i }}</li>
    </ul>
</div>

如果您想将 Controller 用作 ViewModel 而不是范围(我不知道您为什么要这样做),您可以这样做:
$scope.$watchCollection("items", function(newVal, oldVal) {
   ctrl.items = newVal;
});

编辑:

在 Angular 1.3 中,您还可以执行 bindToController: true在指令的定义中, Controller 属性“items”将获得 $scope.items 的双向绑定(bind)得到。然后,你甚至不需要做 this.items = $scope.items; :

您的 forked plunker为了显示。

关于AngularJs:为什么异步数据到达时我的指令内的范围不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940768/

相关文章:

javascript - 从 $watch 触发 ngModelController $parsers 管道

javascript - Angularjs 指令属性属性全部未定义

javascript - Angular http json 请求问题

javascript - 模型更改时angularjs图像src更改

javascript - Meteor Angular & Request - 如何绑定(bind)?

javascript - 基于两种不同形式的NG禁用按钮

javascript - 将对象添加到 $scope 的 2 种方法,只有一种有效

javascript - 如果数据更改,指令中的 ng-repeat 不会更新

javascript - 无法在 ng-repeat 中调用 $scope 函数

javascript - 如果表单无效,则禁用提交按钮 angularjs