gpt4 book ai didi

javascript - 避免在 angularjs 指令中引用父范围

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:01 24 4
gpt4 key购买 nike

我正在编写一条指令,以在名为 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.$parent

有什么方法可以避免引用作用域链上的这么多层吗?

最佳答案

您可以要求父 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
};
...
}]
...
});

关于javascript - 避免在 angularjs 指令中引用父范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19926991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com