Search code examples
angularjsangular-ngmodelng-bind

Angular js unbind and bind dynamically not working


I have an 2 inputs with ng-model and two elements binding the two models, I want that when I click on a button it switch the bindings i a way that element 1 binds model 2 and element 2 bind model 1, it work perfectly, but when start changing models if affect the two elements!

to illustrate it i've created aplunker !

How to fix this ?

app.js :

var app = angular.module('myApp', []);

app.controller('myController', function($scope,$compile) {
  $scope.model1="1";
  $scope.model2="2";

  $('#click').click(function () {

    $('#model1').attr('ng-bind','model2');
    $('#model2').attr('ng-bind','model1'); 
    angular.element($compile( $('#model1'))($scope));
    angular.element($compile( $('#model2'))($scope));
    $scope.$apply();

  });

});

Solution

  • Here is a working plunker example;

    Never manipulate DOM directly in a controller. Usually you don't manipulate dom yourself. You use angular directive to do what you want. Keep it mind that if you want to use jQuery, you're probably doing it in a wrong way and that there is a way do to it from angular without calling to jQuery.

    Javascript

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope,$compile) {
    
    
      $scope.name = 'World';
    
      //input1 and input2 will contain the key of the variable bind to the input.
      $scope.input1 = "value1";
      $scope.input2 = "value2";
      $scope.model = {
         value1 : 1,
         value2 : 2
      }
    
      // Here is my switch function. I just switch the keys and angular will do the rest.
      $scope.switch = function(){
        var tmp = $scope.input1;
        $scope.input1 = $scope.input2;
        $scope.input2 = tmp;
      }
    });
    

    HTML

      <body ng-controller="MainCtrl">
        <!-- Angular provide a directive called ng-click to bind function on clic for the html element -->
        <button ng-click="switch()">switch</button>
        <!-- Here i bind the property of an object. I'll just update the key in input1 to change which property is bind-->
        <input type="text" ng-model="model[input1]" />
        <input type="text" ng-model="model[input2]" />
        <h5 id="model1" ng-bind="model[input1]"></h5>
        <h5 id="model2" ng-bind="model[input2]"></h5>
      </body>
    

    Hope it helped you out, if you want further explanation go on.