Reputation: 774
I can not get the two ways data binding working in AngularJS directive.
Here is my html code from the template, used with a basic controller instantiating mymodel (an array here) :
<select ng-if="mymodel" multipleselect values="mymodel">
I have a directive called 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 :(
});
});
}
}
Why my model is not updated the second time I change it ?
Upvotes: 1
Views: 167
Reputation: 5605
Looking at the answers given I think this will fit your needs without having to use a custom directive:
<select ng-if="mymodel" multiple ng-model="model.mymodel">
Your model will automatically update when the select changes as can be seen here.
The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
Upvotes: 2
Reputation: 25797
You don't need to use jQuery to watch for the change. You can write like this (also to fix your problem):
return {
restrict: 'A',
scope : {
values : '='
},
link : function($scope, element, attrs){
$scope.values = ["some","nice","datas"];
element.on("change", function(){
$scope.values = ["some","amazing","datas"];
});
}
}
Upvotes: 0