我正在写一个指令以在称为djlist
的HTML表中显示来自服务器的数据
directive('djlist', function(urls) {
return {
restrict: 'ACE',
templateUrl: urls.list_objs_template,
scope: {},
controller: ['$scope', '$resource',
function($scope, $resource) {
$scope.objs = $resource(urls.list_objs);
$scope.objs_api = $resource(urls.list_objs_api);
$scope.data = $scope.objs.get();
}
]
};
})
来自服务器的数据显示为
ng-repeat
。数据数组中的每个对象都附加有一个删除按钮,这是另一个称为djdel
的指令<div class="row panel panel-primary">
<h3 class="panel-heading">Data from REST</h3>
<div class="panel-body">
<table class="table">
<tr>
<th>Content</th>
<th>Date Created</th>
<th>Action</th>
</tr>
<tr ng-repeat="d in data.objects">
<td>{{ d.content }}</td>
<td>{{ d.date }}</td>
<td>
<djdel ng-click="del($index)" model-pk="d.id"></djdel>
</td>
</tr>
</table>
</div>
</div>
这是我定义
djdel
的方法directive('djdel', function() {
return {
restrict: 'ACE',
template: '<button class="btn btn-danger btn-small">Delete</button>',
scope: {
modelPk: '='
}, controller: ['$scope', '$http', '$resource',
function($scope, $http, $resource) {
$scope.del = function(index) {
var $parent = $scope.$parent.$parent;
$parent.objs_api.
remove({id: $scope.modelPk}, function() {
$parent.data.objects.splice(index, 1);
});
};
}
]
};
}).
这有效。但是,在从
djdel scope
中启动的对象成功从服务器中删除之后,我需要一种刷新数据集合的方法,该数据集合位于djlist scope
中。作用域层次结构为djlist > ng-repeat > djdel
,因此在引用数据收集时为$scope.$parent.$parent
。有什么方法可以避免在作用域链中引用如此多的级别?
最佳答案
您可以require
父 Controller :在djdel
中:
directive('djdel', function() {
return {
...
require: "^djlist",
...
link: function(scope, elem, attrs, djlistController) {
// the controller function does not have access to the required
// controllers, so we just inject htem in the scope
scope.djlistController = djlistController;
},
controller: ['$scope', '$http', '$resource',
function($scope, $http, $resource) {
// you can access members of the djlistController as
$scope.djlistController.XXX();
...
}]
};
});
在
djlist
中,将所需的函数添加到this
中(不添加到$scope
中):directive('djlist', function(urls) {
...
controller: ['$scope', '$resource',
function($scope, $resource) {
this.XXX = function() {
// you can also add variables here
};
...
}]
...
});