[英]Angularjs: Callback to parent controller
請考慮以下代碼:它具有帶隔離范圍的指令myItem
。 每個項目都將顯示一個按鈕,該按鈕將在指令控制器上調用delete()
。 我想以此觸發外部控制器( AppController
)中的refresh
。 但是由於隔離的范圍,因此當然找不到refresh()
函數。
<html>
<body ng-app="question">
<div ng-cloak ng-controller="AppController">
<my-item ng-repeat="item in list" data="list">
</my-item>
<input type="text" maxlength="50" ng-model="new_item" />
<button ng-click="add(new_item)">+</button>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
(function () {
var app;
app = angular.module('question', []);
app.controller('AppController', [
'$scope', '$http', function ($scope, $http) {
$scope.list = [];
function refresh(){
$http.get('/api/items').then(
function(response){
$scope.list = response.data;
}
);
}
$scope.add = function(item){
$http.post('/api/items', { item: item }).then(refresh);
};
refresh();
}
]);
app.directive('myItem', function() {
return {
scope: {
item: '=data',
},
// directive template with delete button
template: '{{ item }} <button ng-click="delete(item)">-</button>',
restrict: 'E',
// directive controller with delete function
controller: [ '$scope', '$http', function($scope, $http) {
$scope.delete = function (card) {
// This is where it goes wrong! refresh does not exist
$http.delete('/api/items' + card.id).then(refresh);
}
}]
};
});
})();
</script>
</body>
</html>
我可以做的一件事是在myItem指令中添加ng-change,但這將需要使用ngModelController,這似乎有些過分。
我能想到的其他事情:
在指令的scope
屬性中添加onchange: '@'
之類的內容,然后在html中設置onchange = refresh
。 調用onchange表達式,而不是在delete
函數中刷新。 但這感覺就像我在重新實現ng-change
嗎?
在指令中添加require: '^AppController'
。 然后我想我可以直接在父控制器上調用refresh
。 似乎違反了松散耦合。
根本不要使用隔離范圍。 那意味着我們從父范圍繼承並且refresh
可用。 但是,然后我的指令隱式假定范圍將包含一個item
。 這也違反了松散耦合,但是以隱式方式。
所以我的問題是:哪種方法可以讓父控制器知道應該刷新其內容?
海事組織,第一種方法將是最好的方法。 該指令從外部接收一個函數回調,該回調在必要時由該指令執行。 像這樣,這兩個指令是松散耦合的。 它與ng-change相似,后者是ng-model指令使用的屬性。
示例:指令
app.directive('myItem', function() {
return {
restrict: 'E',
scope: {
item: '=data',
myItemDeleteCallback: '&myItemDeleteCallback'
},
template: '{{ item }} <button ng-click="delete(item)">-</button>',
controller: [ '$scope', '$http', function($scope, $http) {
$scope.delete = function (card) {
// This is where it goes wrong! refresh does not exist
$http.delete('/api/items' + card.id).then(function () {
$scope.myItemDeleteCallback();
});
}
}]
};
});
用法:控制器
app.controller('AppController', ['$scope', '$http', function ($scope, $http) {
$scope.list = [];
$scope.refresh = function (){
$http.get('/api/items').then(
function(response){
$scope.list = response.data;
}
);
};
$scope.add = function(item){
$http.post('/api/items', { item: item })
.then($scope.refresh);
};
refresh();
}]);
用法:模板
<div ng-cloak ng-controller="AppController">
<my-item my-item-delete-callback="refresh()" ng-repeat="item in list" data="list">
</my-item>
<input type="text" maxlength="50" ng-model="new_item" />
<button ng-click="add(new_item)">+</button>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.