如何正确使用隔离范围属性?
我有一个指令,从页面控制器调用,传递给它的属性item
,例如<my-directive item="myItem"></my-directive>
,包含id
。
下面的代码不起作用,因为在控制器中似乎未定义$scope.item
..就像我太早使用它一样。当我想使用它时,我怎么能确定它实际上已经设置好了?
app.directive('myDirective', [function() {
return {
restrict: 'E',
templateUrl: 'template.html',
scope: {
item: "="
},
controller: ['$scope', 'ExtendedItemFactory', function($scope, ExtendedItemFactory) {
this.extendedInfo = ExtendedItemFactory.get({ id: $scope.item.id });
}],
controllerAs: 'MyDirectiveCtrl'
};
}]);
答案 0 :(得分:1)
您可以在指令中使用$watch
来监视价值变化&amp;将触发您想要的代码。
<强>代码强>
app.directive('myDirective', [function() {
return {
restrict: 'E',
templateUrl: 'template.html',
scope: {
item: "="
},
controller: ['$scope', 'ExtendedItemFactory', function($scope, ExtendedItemFactory) {
this.extendedInfo = ExtendedItemFactory.get({
id: $scope.item.id
});
$scope.$watch('item', function(newVal, oldVal) {
if (newVal && newVal != oldVal)
this.extendedInfo = ExtendedItemFactory.get({
id: $scope.item.id
});
}, true).bind(this);
}],
controllerAs: 'MyDirectiveCtrl'
};
}]);
答案 1 :(得分:0)
您正在使用controllerAs,因此您不需要在此实例中注入$ scope。
我会将您的指令定义更改为以下内容,注意使用bindToController,这将确保您的隔离范围值已填充并在控制器上可用:
app.directive('myDirective', [function() {
return {
restrict: 'E',
templateUrl: 'template.html',
scope: {
item: "="
},
controller: ['ExtendedItemFactory', function(ExtendedItemFactory) {
this.extendedInfo = ExtendedItemFactory.get({ id: this.item.id });
}],
controllerAs: 'MyDirectiveCtrl',
bindToController: true
};
}]);
答案 2 :(得分:0)
当指令加载时,您可以创建可根据需要检索它的getter函数,而不是初始化extendedInfo
。
this.getExtendedInfo = function(){
return ExtendedItemFactory.get({ id: $scope.item.id });
}
或者,您可以在item
准备好
<div ng-if="ctrl.item">
<my-directive item="ctrl.item"></my-directive>
</div>