如何在Angular.js中设置元素的值

nel*_*nic 2 javascript frontend angularjs

为什么我不能在Angular.js中这样做:

document.getElementById('divid').value = 'Change Text to This';
Run Code Online (Sandbox Code Playgroud)

什么是"正确"(Angular)的做法?

ABu*_*cin 5

在Angular中,您使用该ng-model指令来创建模型(即JS变量)和视图(即<div>)之间的双向数据绑定.基本上,这意味着无论何时更改视图中的数据(例如通过输入),更改都将反映在JS变量中.见下文:

HTML:

<html ng-app="myApp">
    <div ng-controller="MyCtrl">
        <div>{{myVariable}}</div>
        <input type="text" ng-model="myVariable" />
    </div>
</html>
Run Code Online (Sandbox Code Playgroud)

JS:

/* App global module */
var myApp = angular.module('myApp');

/* Define controller to process data from your view */
myApp.controller('MyCtrl', function($scope) {

   $scope.myVariable = "initialValue"; // this is the variable that corresponds to text inserted in your input

});
Run Code Online (Sandbox Code Playgroud)

在这里,myVariable将"initialValue"作为初始值.对输入的任何进一步更改都将覆盖此变量的值.

另请注意,{{myVariable}}将数据注入到div中.更改输入中的值时,div文本也将更改.