1

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 ?

ValentinV
  • 764
  • 1
  • 8
  • 17
  • Where did you define your `mymodel` property ? As you're using 2-way binding in your directive, there should be `mymodel` property defined on the scope of the enclosing/parent element of your `multipleselect` directive. – Arkantos Jan 20 '16 at 13:19
  • Ive had issues in the past with `ng-if` and 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 the `ng-if`. Could cause memory leaks. – ste2425 Jan 20 '16 at 13:24

2 Answers2

2

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?

Community
  • 1
  • 1
Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
0

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"];
    });
   }
}
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121