Search code examples
angularjsangular-ngmodelangularjs-ng-model

Is it possible to bind and unbind an element on button click? - AngularJS


I created a display text and an input field and bind them together with ng-model as follow.

HTML

  <div ng-app ng-controller="test">
    <div ng-bind="content"></div>
    <input id="txtElem" type="text" ng-model="content">
        <button ng-click="stopBinding()"> Unbind</button>
        <button ng-click="binding()"> Bind </button>
  </div>

JS

function test( $scope ) {
    $scope.content = 'Welcome';

     $scope.binding = function() {
       angular.element(document.getElementById('txtElem')).bind();
    };

    $scope.stopBinding = function() {
       angular.element(document.getElementById('txtElem')).unbind();
    };
};

Display

enter image description here

I found this(http://jsfiddle.net/jexgF/) for unbind method, but don't know how to bind it again, if "Bind" button is clicked. Anyone could help?

Apart from bind and unbind between elements of <div> and <input>, anyone know how to bind and unbind two <input> fields?


Solution

  • I'm not sure where the test() function in your example resides, but it is not a good idea - an anti-pattern, in fact - to manipulate the DOM in the controller.

    The proper way is to create a variable, separate from the input variable content, represents the preview part.

    You could do this simply in the View; if this logic, in your opinion, is a View-only logic. lastBound represents the last bound value of content:

    <div ng-init="binding = true">
       <input ng-model="content">
       <button ng-click="binding = false">Unbind</button>
       <button ng-click="binding = true">Bind</button>
    
       <div ng-bind="lastBound = (binding && content) || lastBound"></div>
    </div>
    

    (the use of ng-init here is just for illustration purposes - you should set binding in the controller).

    EDIT:

    If the intent is to bind to another ng-model, then the solution is different, but not dissimilar. You still need to use 2 variables:

    <input ng-model="content" ng-change="preview = (binding && content) || preview">
    <input ng-model="preview" ng-change="content = (binding && preview) || content">