Javascript 避免在angularjs指令中引用父范围
我正在编写一个指令,在名为Javascript 避免在angularjs指令中引用父范围,javascript,angularjs,Javascript,Angularjs,我正在编写一个指令,在名为djlistHTML表中显示来自服务器的数据 directive('djlist', function(urls) { return { restrict: 'ACE', templateUrl: urls.list_objs_template, scope: {}, controller: ['$scope', '$resource', function($scope,
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>
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作用域中启动)后,我需要一种方法来刷新数据收集,该数据收集在djlist作用域中。作用域层次结构是djlist>ng repeat>djdel
,因此在引用数据收集时$scope.$parent.$parent
有什么方法可以避免引用范围链上的这么多级别吗?您始终可以尝试在应用程序的$rootScope
中发出事件
$rootScope.$broadcast("nameOfTheEvent", paramsToSend);
就在你从服务器上删除一些东西之后
$rootScope.$on("nameOftheEvent", function(paramsToRecieve) { refreshList();});
当然,paramsToRecieve是paramsToSend,可以是任何对象。您可以要求父控制器:在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
中,将所需功能添加到中(而不是添加到$scope
):
$rootScope上调用的方法应为$broadcast not emit。发射上升,广播下降$根范围是顶级范围,所以需要广播。非常干净。非常感谢。
directive('djlist', function(urls) {
...
controller: ['$scope', '$resource',
function($scope, $resource) {
this.XXX = function() {
// you can also add variables here
};
...
}]
...
});