2013-09-25 87 views
1

我有一個指令,該屬性包含一個範圍名稱,我希望在指令中設置了某些內容時進行更新。將範圍名稱更新爲指令

<div data-my-directive data-scope-var-to-update="my_scope_variable"></div> 



.directive('myDirective', function($rootScope){ 
     return function(scope, element, attrs){ 

      var scope_var_name = attrs.scopeVarToUpdate; 

      scope[scope_var_name] = 'This message was updated from the directive'; 
     } 
    }) 

以上允許我做我想要的只有當範圍變量不包含任何點符號。

我的問題是如何修改上述以滿足包含點符號的範圍變量,例如$ scope.a.b?

<div data-my-directive data-scope-var-to-update="a.b"></div> 

上述背後的想法是在任何範圍內的變量名傳遞,並從該指令更新一次它完成它的工作,這意味着新的分配應該由家長控制訪問。

+1

我想你不得不解析字符串並在每個單獨的對象。像a = {}然後a.b =「這條消息更新....」。 –

+0

@CraigSquire幸運的是,angular有一個函數,'scope。$ eval' –

回答

1

您需要使用$解析服務點符號模型。像這樣的事情在你的指令,這在這裏http://docs.angularjs.org/api/ng

var getter = $parse(parseattrs.scopeVarToUpdate); 
var setter = getter.assign; 
getter(scope); //get value 
setter(scope,'value'); //set value 

查看文檔。$解析

+0

我喜歡這個答案,我不得不爲自己嘗試一下,因爲我之前沒有使用解析服務。 http://plnkr.co/edit/BaKc7GEt5zXnnhQxJHBk –

+0

接受此答案,因爲這爲我工作,謝謝。 – Malcr001

1

您使用scope.$eval(attrs.scopeVarToUpdate)

.directive('myDirective', function(){ 
    return function(scope, element, attrs){ 
     scope.$eval(attrs.scopeVarToUpdate) = 'This message was updated from the directive'; 
    } 
}) 

或者使用具有雙向綁定一個孤立的範圍,不用擔心任何的。 隔離範圍版本:

.directive('myDirective', function(){ 
    return{ 
     scope:{scopeVarToUpdate:'='}, 
     link: function(scope, element, attrs){ 
     scope.scopeVarToUpdate = 'This message was updated from the directive'; 
     } 
    } 
}) 
+0

對於我得到的第一個選項: Uncaught ReferenceError:在賦值中無效的左手邊 – Malcr001

+0

啊,試試'var model = scope。$ eval (attrs.scopeVarToUpdate); model ='whatever';' –