2014-01-10 105 views
0

通过指令分配新值的最佳方式是什么?双向数据绑定。更改指令中的范围值

我在这里有一个小提琴,我试过。 http://jsfiddle.net/user1572526/grLfD/2/。但它并不奏效。

我的指令:

myApp.directive('highlighter', function() { 
    return { 
     restrict: 'A', 
     replace: true, 
       scope: { 
        activeInput: '=' 
       }, 
     link: function (scope, element, attrs) { 
      element.bind('click', function() { 
       scope.activeInput = attrs.setInput 
      }) 
     } 
    } 
}); 

而且我的控制器:

function MyCtrl($scope) { 
      $scope.active = { 
       value : true 
      }; 
} 

而我的观点:

<h1 highlighter active-input="active.value" set-input="false">Click me to update Value in scope: {{active}}</h1> 

所以我要做的就是更新与给定的scope.active属性setInput。

任何想法我在做什么错在这里?

+0

[Using scope。$ watch and scope。$ apply](http://stackoverflow.com/questions/15112584/using-scope-watch-and-scope-apply) – Stewie

回答

2

随着element.bind你离开Angular的领域,所以你需要告诉Angular发生了什么事情。你这样做,与scope.$apply功能:

scope.$apply(function(){ 
    scope.activeInput = attrs.setInput; 
}); 

这里是一个updated jsfiddle

+0

@DavinTryon感谢您的输入。 – Stewie

+0

:),当你的答案出现时,在剪贴板中有链接! –

+0

@DavinTryon我想这是一场比赛。还是一个非常好的姿态,以一个例子来更新我的答案。但最终,问题可能会以无用的方式关闭。 :) – Stewie