最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS data binding by DOM manipulation - Stack Overflow

programmeradmin4浏览0评论

When I type some string to input element directly, two-way data binding of AngularJS works very well. But when I change value of input element by javascript code, two-way binding does not work. Is there a good way for doing this?

html code:

<div ng-app ng-controller="Ctrl">
    <input id="inputElem" ng-model="modelName" type="text"/>
    <span>{{modelName}}</span>
</div>

javascript code:

function Ctrl($scope) {
    $scope.modelName = "";
}

function foo() {
    // THIS DOES NOT TRIGGER ANGULAR DATA-BINDING!!!!
    $("#inputElem").val("THIS IS DOM MANIPULATION");
}

When I type some string to input element directly, two-way data binding of AngularJS works very well. But when I change value of input element by javascript code, two-way binding does not work. Is there a good way for doing this?

html code:

<div ng-app ng-controller="Ctrl">
    <input id="inputElem" ng-model="modelName" type="text"/>
    <span>{{modelName}}</span>
</div>

javascript code:

function Ctrl($scope) {
    $scope.modelName = "";
}

function foo() {
    // THIS DOES NOT TRIGGER ANGULAR DATA-BINDING!!!!
    $("#inputElem").val("THIS IS DOM MANIPULATION");
}
Share Improve this question asked Mar 27, 2013 at 10:50 firia2000firia2000 1,9235 gold badges20 silver badges22 bronze badges 1
  • 2 This not the way you do it in angularjs, instead of changing teh value of the input field you need to change the value of the binded field – Arun P Johny Commented Mar 27, 2013 at 11:08
Add a ment  | 

4 Answers 4

Reset to default 5

You can achieve this by triggering the change event

$("#inputElem").val("THIS IS DOM MANIPULATION").trigger('change');

Demo: Plunker

Another hack to modify the binded value

var scope = angular.element('#inputElem').scope();
scope.$apply(function(){
  scope.modelName = "THIS IS DOM MANIPULATION";
});

Demo: Plunker

You're really supposed to change the model for that rather than the other way around:

http://jsfiddle/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.

From the docs:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

http://docs.angularjs/api/ng.$rootScope.Scope

You can use the ngChange directive for that: http://docs.angularjs/api/ng.directive:ngChange

发布评论

评论列表(0)

  1. 暂无评论