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

痞子三分冷 提交于 2019-12-25 02:48:15

问题


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

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?


回答1:


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">


来源:https://stackoverflow.com/questions/29360311/is-it-possible-to-bind-and-unbind-an-element-on-button-click-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!