AngularJS共享指令范围和迭代值

时间:2013-11-20 16:17:37

标签: javascript angularjs angularjs-directive

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

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>

此示例的目的是在单击directive2时将更多帖子加载到directive1范围。问题是,我收到了这个错误:

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

导致这种情况的原因是什么?我应该如何修复它?

1 个答案:

答案 0 :(得分:1)

一种方法是使用directive2 require directive1,以便它可以与directive1控制器通信。这允许directive1拥有posts,就像在你的例子中一样,同时启用指令2来添加它,从而为我们提供了很好的责任分离。

所以我们将它添加到directive2

 require: "^directive1",

然后在directive1上,我们使用addPosts添加一个带有setter方法(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;
       });

然后我们可以通过将其作为参数添加到您的链接来访问directive1的控制器:

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

最后从指令2调用addPosts

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

这是工作小提琴:http://jsfiddle.net/Dggp6/