我有一个带有隔离范围的指令,该指令通过引用获取范围变量
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>
在外部控制器中,数据被异步加载,并且传递给指令的合并范围项已更新:
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>
如何在我的指令中获取我的范围以进行更新?我会吗
当Angular第一次运行指令的控制器函数(即your $scope.items === undefined
)时this.items = $scope.items
,this.items === undefined
也是如此。
而已。之后,没有任何变化this.items
。
这不一样$scope.items
。$scope.items
是双向绑定到外部范围的,因此,每当Angular在外部检测到更改时,它将设置隔离的范围变量。
最简单的方法(我认为最合适的方法)是$scope
直接在指令中使用属性:
<div>
Inside directive
<ul ng-repeat="i in items">
<li>{{ i }}</li>
</ul>
</div>
如果要将控制器用作ViewModel而不是范围(我不知道为什么),可以执行以下操作:
$scope.$watchCollection("items", function(newVal, oldVal) {
ctrl.items = newVal;
});
编辑:
在Angular 1.3中,您也可以bindToController: true
在指令的定义中进行操作,以便控制器属性“ items
”将获得所获得的双向绑定$scope.items
。然后,您甚至不需要执行以下操作this.items = $scope.items;
:
您的叉形拨叉器进行说明。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句