2016-03-15 51 views
0

這段代碼只是一個測試,我將它放在一起以便理解邏輯。 基本上我想要發生的是獲取傳入指令的值。基於該值,我想添加幾個屬性到範圍。如何更新鏈接方法中的範圍屬性?

這第一個測試只是爲了更新已經傳入的屬性

指令:

angular.module('bd.common') 

    .directive('bdPopoverLegend', function() { 
     return { 
      restrict: 'AE', 
      replace: true, 
      scope: { 
       legendInfo: '=info' 
      }, 
      templateUrl: '/bd/common/ctl/bdPopoverLegend.html', 
      link: function (scope, element, attrs) { 
       scope.legendInfo.test = 'hello world 4'; 
      } 
     }; 
    }); 

模板:

<div>{{legendInfo.test}}</div> 

調用指令:

<div bd-popover-legend="" info="{test: 'hello world 3'}"> 

值不會改變,它保持爲「你好世界3」而不是「世界你好4」

+0

只要不傳遞常量「=」結合。將其更改爲'&',您的示例將會起作用。或者傳遞範圍變量{test:...} –

+0

我不理解,你能告訴我一個例子嗎?此外,最終,我想添加屬性到指令中使用的範圍。這仍然適用? – Smeegs

+0

http://plnkr.co/edit/GsQjHYfJFKJxSyUe6wJC?p=preview這是通常使用的綁定。如果你想以另一種方式來做 - 這取決於你。 –

回答

1

試試這個:

.directive('bdPopoverLegend', function() { 
    return { 
     restrict: 'AE', 
     replace: true, 
     scope: { 
      legendInfo: '=info' 
     }, 
     templateUrl: '/bd/common/ctl/bdPopoverLegend.html', 
     link: function (scope, element, attrs) { 

      scope.$watch('legendInfo', function (watchInfo) { 
       watchInfo.test = 'hello world 4'; 
      }); 

     } 
    }; 
}); 
+0

它會拋出一個錯誤,watchInfo是undefined – Smeegs

+0

好的,你不需要在它內部編寫範圍。我會更新答案 –

+0

值得注意的是,這是一個ng-repeat。無論如何,我收到一個10 $ digest()interations達到的錯誤。中止! – Smeegs