2013-05-11 52 views
17

如何在指令中設置插值值?我可以從下面的代碼中讀取正確的值,但我無法設置它。如何在角度指令中設置插值?

JS:

app.directive('ngMyDirective', function() { 
    return function(scope, element, attrs) { 
     console.log(scope.$eval(attrs.ngMyDirective)); 

     //set the interpolated attrs.ngMyDirective value somehow!!! 
    } 
}); 

HTML:

<div ng-my-directive="myscopevalue"></div> 

其中myscopevalue是我的控制器的範圍值。

回答

24

如果你想設置的範圍值,但不知道屬性(提前)的名稱,你可以使用object[property]語法:

scope[attrs.myNgDirective] = 'newValue'; 

如果字符串屬性包含一個點(例如myObject.myProperty),這不起作用;您可以使用$eval做一個任務:

// like calling "myscopevalue = 'newValue'" 
scope.$eval(attrs.myNgDirective + " = 'newValue'"); 

[更新:你真的應該使用$parse代替$eval。見Mark's answer]

如果您使用的是分離的範圍,你可以使用=註釋:

app.directive('ngMyDirective', function() { 
    return { 
     scope: { 
      theValue: '=ngMyDirective' 
     }, 
     link: function(scope, element, attrs) { 
      // will automatically change parent scope value 
      // associated by the variable name given to `attrs.ngMyDirective` 
      scope.theValue = 'newValue'; 
     } 
    } 
}); 

你可以看到this Angular/jQuery color picker JSFiddle example這樣的一個例子,其中分配給scope.color裏面的指令自動更新該變量通過轉換爲控制器範圍的指令。

+0

scope [attrs.myNgDirective] ='newValue';成功了!儘管myNgDirective的值必須直接在作用域上,而不是作用域的子對象。這是有道理的 – Anton 2013-05-11 07:02:07

+0

我相信你應該能夠'$ eval'賦值表達式的對象符號;我會更新我的答案。 – 2013-05-11 07:03:56

+0

那會很酷。像範圍。$ eval(attrs.ngMyDirective ='new value')? – Anton 2013-05-11 07:16:25

45

只要指令不使用隔離範圍,並且使用屬性指定範圍屬性,並且想要更改該屬性的值,則建議使用$parse。 (我覺得語法比$ EVAL的更好。)

app.directive('ngMyDirective', function ($parse) { 
    return function(scope, element, attrs) { 
     var model = $parse(attrs.ngMyDirective); 
     console.log(model(scope)); 
     model.assign(scope,'Anton'); 
     console.log(model(scope)); 
    } 
}); 

fiddle

$parse作品的屬性是否包含一個點。

+0

有趣的東西。感謝你的回答。您可能有一個觀點,認爲解析可能是比eval更好的術語/語法。歡呼 – Anton 2013-05-11 23:19:35

+3

這絕對是實現'='沒有範圍隔離的正確方法。 – 2013-11-26 13:43:59

+0

我必須在'model.assign(...)'之後添加'scope。$ apply()',以便在視圖中反映我的指令更改。有沒有更清潔的解決方案? – Juljan 2014-05-18 07:12:27