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) :
HTML
<select ng-if="mymodel" multipleselect values="mymodel">
DIRECTIVE
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 ?
mymodelproperty ? As you're using 2-way binding in your directive, there should bemymodelproperty defined on the scope of the enclosing/parent element of yourmultipleselectdirective.ng-ifand such things like this, it will remove the actual element from the DOM and replace it. Don't know if it could be a similar issue. Also just so you know your change will fire for every select on the page. You should use the element object to scope your event to the directive. You should also listen to the destroy to event to remove the handler when it is remove in theng-if. Could cause memory leaks.