【问题标题】:AngularJS directive scope not updating it's templateAngularJS 指令范围没有更新它的模板
【发布时间】:2014-09-01 02:05:00
【问题描述】:

在 AngularJS 中,我可以成功地将数据从控制器绑定到指令。我还可以在指令中设置其他 $scope 属性并将它们反映在模板中最初。

但是,当我通过指令更新范围时(在最初加载所有内容之后),这些更改不会应用到模板中。

例如...

控制器

app.controller('FooCtrl',function($scope){
    $scope.bar = ['one','two','three'];
});

指令

app.directive('fooDirective',function($window){
  return {
    restrict: 'AE',
    replace: true,
    transclude: 'element',
    scope: {
      foo: "="
    },
    template: '<h1>{{foo}} - {{test}}</h1>',
    link: function(scope, element, attrs, ctrl){

      scope.test = 3;

      angular.element($window).bind('resize',function(){
        console.log('the screen has resized');
        scope.test = scope.test + 1;
      });
    }
  };
});

HTML

<body ng-controller="FooCtrl">
    <foo-directive data-foo="bar"></foo-directive>
</body>

所有这些代码都使用来自控制器范围和指令范围的数据正确地呈现模板。当我调整页面大小时,console.log 被命中,但范围更新未反映在模板中。为什么会这样?我该如何解决这个问题?

这是plunker example

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    由于您是在 Angular 上下文之外处理 jQuery 事件,因此您需要调用 $apply 来触发 $digest:

    link: function(scope, element, attrs, ctrl){
    
      scope.test = 3;
    
      angular.element($window).bind('resize',function(){
        scope.$apply(function() {
            console.log('the screen has resized');
            scope.test = scope.test + 1; 
        });
    
      });
    }
    

    Updated Plunker

    【讨论】:

    • 这似乎可以解决问题!很难知道 Angular 什么时候会为你调用 $apply()。
    • 我不确定这是否有帮助,但我提供了一个关于何时可以在此处调用 $apply 的答案:stackoverflow.com/questions/24295145/…
    猜你喜欢
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 2015-02-04
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多