如何在指令中访问ng-repeat之外的范围

时间:2014-11-07 17:28:50

标签: angularjs

我有一个角度指令和一个项目列表:

<li ng-repeat="x in topics">
  <p change-content-on-click>{{ x.name }}</p>
</li>

app.directive('changeContentOnClick', function(TopicService) {
   return{
       restrict: 'A',
       link: function(scope, element) {
           element.bind('click', function(){
               scope.message = "hello";
               scope.$apply();
           });
       }
   }
});

我需要做的是将重复之外的{{ message }}绑定到列表中单击的项目。我怎样才能做到这一点?我经历了很多文档但我无法找到。

1 个答案:

答案 0 :(得分:2)

将其作为具有双向数据绑定的属性传递

<li ng-repeat="x in topics">
  <p change-content-on-click some-attr="message">{{ x.name }}</p>
</li>

<div ng-bind='message'></div> <!-- same as {{message}} but less messy on failure -->

JS:

$scope.message = {text:""}; 

app.directive('changeContentOnClick', function() {
   return{
       restrict: 'A',
       scope: { 
           someAttr: "=" 
       },
       link: function(scope, element) {
           element.bind('click', function(){
               scope.message = "hello";
               scope.someAttr.text = scope.message;
               scope.$apply(); // not sure that you need this
               console.log(scope.message);
           });
       } 
   } 
});

更新:
根据以下评论修正,你是对的,忘了你不能只分配给字符串,需要一个对象。

http://plnkr.co/edit/1qTLzk41jzrWiGLRiZG9?p=preview