单击按钮是否可以绑定和取消绑定元素? -AngularJS [英] Is it possible to bind and unbind an element on button click? - AngularJS
问题描述
我创建了一个显示文本和一个输入字段,并将它们与ng-model绑定在一起,如下所示.
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();
};
};
显示
我找到了此方法( http://jsfiddle.net/jexgF/)用于取消绑定方法,但是如果单击绑定"按钮,则不知道如何再次绑定它.有人可以帮忙吗?
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?
除了<div>
和<input>
元素之间的绑定和取消绑定之外,还有谁知道如何绑定和取消绑定两个<input>
字段?
Apart from bind and unbind between elements of <div>
and <input>
, anyone know how to bind and unbind two <input>
fields?
推荐答案
我不确定示例中的test()
函数位于何处,但这不是一个好主意-实际上是一种反模式-在控制器中操作DOM.
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.
正确的方法是创建一个与输入变量content
分开的变量,该变量代表预览部分.
The proper way is to create a variable, separate from the input variable content
, represents the preview part.
您可以仅在View中执行此操作;如果您认为此逻辑是仅查看逻辑. lastBound
表示content
的最后一个边界值:
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>
(此处使用ng-init
只是出于说明目的-您应在控制器中设置binding
).
(the use of ng-init
here is just for illustration purposes - you should set binding
in the controller).
如果目的是绑定到另一个ng-model
,则解决方案是不同的,但没有什么不同.您仍然需要使用2个变量:
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">
这篇关于单击按钮是否可以绑定和取消绑定元素? -AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!