在angularjs重新呈现由$ scope触发的模板后,如何运行函数。$ watch?

时间:2014-04-13 19:07:25

标签: angularjs

以下是一个例子:

<div my-directive my-attr="someNumericValueFromParentScopeVariable">
  <div class="container">
    <div ng-repeat="item in items">
      {{item.id}}
    </div>
  </div>
</div>

angular.directive( "myDirective", function(){
  return {
    scope : {
      myAttr : "="
    },
    controller : function($scope){
      $scope.$watch( "myAttr", function( newValue, oldValue, scope ) {
        var newItems = []; // contruct new array with n-size
        scope.items = newItems;
        // After this, the template will be rerendered. 
        // I want to recompute the new width of the div container and store it in the scope.
      }
    }
  };
});

如果my-attr指向范围变量并进行修改,则scope.items将被替换,<div ng-repeat="item in items">将被重新呈现。在<div class="container">呈现其元素后,如何计算元素<div ng-repeat="item in items">的新宽度?我需要在$scope.$watch对模型进行更改之后以及模型因模型更改而重新呈现之后执行此计算。

还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以在使用$ timeout服务呈现列表后调用函数:

$scope.$watchCollection( 'things', function(){
    $timeout( function(){
        // calculate width here
    });
});

Fiddle