[英]AngularJS data binding by DOM manipulation
When I type some string to input element directly, two-way data binding of AngularJS works very well. 当我直接在输入元素中键入一些字符串时,AngularJS的双向数据绑定效果很好。 But when I change value of input element by javascript code, two-way binding does not work.
但是,当我通过javascript代码更改输入元素的值时,双向绑定不起作用。 Is there a good way for doing this?
有一个好的方法吗?
html code: html代码:
<div ng-app ng-controller="Ctrl">
<input id="inputElem" ng-model="modelName" type="text"/>
<span>{{modelName}}</span>
</div>
javascript code: JavaScript代码:
function Ctrl($scope) {
$scope.modelName = "";
}
function foo() {
// THIS DOES NOT TRIGGER ANGULAR DATA-BINDING!!!!
$("#inputElem").val("THIS IS DOM MANIPULATION");
}
You can achieve this by triggering the change event 您可以通过触发更改事件来实现
$("#inputElem").val("THIS IS DOM MANIPULATION").trigger('change');
Another hack to modify the binded value 另一个修改绑定值的技巧
var scope = angular.element('#inputElem').scope();
scope.$apply(function(){
scope.modelName = "THIS IS DOM MANIPULATION";
});
You're really supposed to change the model for that rather than the other way around: 您真的应该为此更改模型,而不是相反:
http://jsfiddle.net/b9chris/EBWtR/ http://jsfiddle.net/b9chris/EBWtR/
<div ng-app>
<div ng-controller=Ctrl>
<div><input ng-model=thing /></div>
<div ng-bind=thing></div>
</div>
</div>
function Ctrl($scope) {
$scope.thing = 'Hi';
// Later, for some reason you want to change the
// input in code so you update the model
setTimeout(function() {
$scope.thing = 'Bye';
$scope.$apply();
}, 2000);
}
When you change something outside of angular, you have to call $apply on the $scope, to have your changes applied. 当您更改角度范围以外的内容时,必须在$ scope上调用$ apply,以应用您的更改。
From the docs: 从文档:
$apply() is used to execute an expression in angular from outside of the angular framework.
$ apply()用于从角度框架外部以角度执行表达式。 (For example from browser DOM events, setTimeout, XHR or third party libraries).
(例如,来自浏览器DOM事件,setTimeout,XHR或第三方库)。
http://docs.angularjs.org/api/ng .$rootScope.Scope http://docs.angularjs.org/api/ng。$ rootScope.Scope
您可以为此使用ngChange指令: http ://docs.angularjs.org/api/ng.directive:ngChange
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.