javascript – 避免在angularjs指令中引用父作用域
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 避免在angularjs指令中引用父作用域,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2176字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 避免在angularjs指令中引用父作用域](/upload/InfoBanner/zyjiaocheng/817/33a89e016ed84f93b97ca8b19b476bce.jpg)
我正在编写一个指令,用于在名为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作用域中启动的服务器中成功删除后,我需要一种方法来刷新数据集合,这是在djlist范围内.范围层次结构是djlist> ng-repeat> djdel,因此$scope.$parent.引用数据收集时的父级.
有没有办法避免引用范围链上的这么多级别?
解决方法:
您可以要求父控制器:在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):
directive('djlist', function(urls) {
...
controller: ['$scope', '$resource',
function($scope, $resource) {
this.XXX = function() {
// you can also add variables here
};
...
}]
...
});
内容总结
以上是互联网集市为您收集整理的javascript – 避免在angularjs指令中引用父作用域全部内容,希望文章能够帮你解决javascript – 避免在angularjs指令中引用父作用域所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。