我無法獲得在AngularJS指令中工作的兩種數據綁定方式。AngularJS指令中的數據綁定的兩種方式
下面是從模板我的HTML代碼,一個基本的控制器實例爲MyModel(這裏的數組)使用:
HTML
<select ng-if="mymodel" multipleselect values="mymodel">
DIRECTIVE
我有一個指令稱爲multipleselect:
return {
restrict: 'A',
scope : {
values : '='
},
link : function($scope, element, attrs){
...
$scope.values = ["some","nice","datas"]; //Actually works, the model is changed in the controller
$("select").change(function(){ //This is a callback, asynchronous situation
$scope.$apply(function() { //Using apply to notify the controller that we are changing its model
$scope.values = ["some","amazing","datas"]; //Not working :(
});
});
}
}
爲什麼我的模型沒有更新第二個tim我改變它了嗎?
你在哪裏定義'mymodel'財產?由於您在指令中使用了雙向綁定,因此應該在'multipleselect'指令的封閉/父元素範圍內定義'mymodel'屬性。 – Arkantos
我過去用'ng-if'和類似的東西出現了問題,它會從DOM中刪除實際的元素並將其替換。不知道它是否可能是一個類似的問題。也只是爲了讓您知道您的更改會針對頁面上的每個選項啓動。您應該使用元素對象來將您的事件範圍限定爲指令。你也應該聽取銷燬事件,以便在「ng-if」中刪除處理程序時移除該處理程序。可能導致內存泄漏。 – ste2425