2014-03-26 40 views
2

我試圖創建一個角度指令,我可以通過單個選項對象或通過某些屬性來設置選項。這是什麼樣的代碼示例:Angular JS指令,更改鏈接函數中的雙向數據綁定

app.directive('testElement', [function() { 
    return { 
     restrict: "E", 
     scope: { 
      options: "=" 
     }, 
     template: "<p><span>Name: </span>{{ options.name }}</p>", 
     link: function (scope, element, attrs) { 
      scope.options = scope.options || {}; 
      if (attrs.name) 
       scope.options.name = attrs.name; 
     } 
    }; 
}]); 

這工作得很好,因爲如果我通過在一個名字通過選項屬性名稱值顯示。但是,如果我通過name屬性傳遞一個名稱,即使鏈接函數修改了選項,該值也不會呈現。

http://plnkr.co/edit/IMVZRdAW2a5HvSq2WtgT?p=preview

我覺得我失去了一些東西在數據的選項結合2的方式是如何工作的根本。

回答

6

如果你沒有通過雙向數據綁定,角生氣:

https://github.com/angular/angular.js/issues/1435

使用另購的結合(=?):

app.directive('testElement', [function() { 
    return { 
     restrict: "E", 
     scope: { 
      options: "=?" 
     }, 
     template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>", 
     link: function (scope, element, attrs) { 
      scope.options = scope.options || {}; 
      if (attrs.name) 
       scope.options.name = attrs.name; 
     } 
    }; 
}]); 

或者,如果您使用的是老版本的角度,在$ attrs上使用$ eval。選項:

app.directive('testElement', [function() { 
    return { 
     restrict: "E", 
     //Still can create isolate scope to not clobber parent scope variables. 
     scope: {}, 
     template: "<p><span>Name: </span>{{ options.name }}{{ test }}</p>", 
     link: function (scope, element, attrs) { 
      scope.options = scope.$eval(attrs.options) || {}; 
      if (attrs.name) 
       scope.options.name = attrs.name; 
     } 
    }; 
}]); 
+0

你可以用= ?,看我的回答 – Chandermani

+0

啊!謝謝,現在全部排序。 –

+0

使用可選的雙重綁定時,永遠不會傳遞該值(v1.3.10)。範圍:{ selectedValue:'=?selectedValue' }。在刪除?時有效。任何想法如何發生? – Vincent