gpt4 book ai didi

javascript - AngularJS 共享指令范围和迭代值

转载 作者:行者123 更新时间:2023-11-28 01:47:32 25 4
gpt4 key购买 nike

我正在尝试创建一个指令,该指令从子指令中获取值并填充 View 中的字段。一个例子:

app.directive('directive1',function() {
return {
restrict: "A",
scope:{posts :'='},
link: function (scope, element, attrs) {
scope.posts = {};
}
};
});


app.directive('directive2',function() {
return {
restrict: "A",
link: function (scope, element, attrs) {

element.bind('click', function(e) {
e.preventDefault();
scope.posts = {
'1' : {'title' : 'Cat in Hat'},
'2' : {'title' : 'Boat In Like'}
};
});
}
};
})

HTML

<div directive1>
<div ng-repeat="post in posts track by $index" class="item"><div ng-include="\'/templates/post.html\'"></div>

<div directive2>Load More Posts</div>
</div>

此示例的目的是在单击指令 2 时将更多帖子加载到指令 1 范围中。问题是,我收到此错误:

[$compile:nonassign] Expression 'undefined' used with directive 'directive1' is non-assignable!

造成这种情况的原因是什么?我应该如何解决它?

最佳答案

一种方法是使用指令 2 require 指令 1,以便它可以与指令 1 Controller 进行通信。这允许指令 1 拥有帖子,就像您在示例中一样,同时允许指令 2 添加到其中,从而使我们能够很好地分离职责。

所以我们将其添加到指令2

 require: "^directive1",

然后在指令 1 上,我们添加一个带有 setter 方法 (addPosts) 的 Controller ,使用 extend 添加新帖子,然后将新合并的对象放在范围(使用 $apply 因为我们通过点击事件触发它:

  controller: function($scope){
var posts = {'0' : {'title' : "Oh the Places Youll Go"}};
this.addPosts = function($scope,newPosts) {
angular.extend(posts,newPosts);
$scope.$apply(function() {
$scope.posts = posts;
});

然后我们可以通过将指令1作为参数添加到您的链接来访问它的 Controller :

 link: function (scope, element, attrs, controller) {...}

最后从指令 2 调用 addPosts:

  var newPosts = {
'1' : {'title' : 'Cat in Hat'},
'2' : {'title' : 'Boat In Like'}
};
controller.addPosts(scope,newPosts);

这是工作 fiddle :http://jsfiddle.net/Dggp6/

关于javascript - AngularJS 共享指令范围和迭代值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20101159/

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