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

时间:2014-08-01 12:07:45

标签: javascript angularjs frontend

为什么我不能在Angular.js中执行此操作:

document.getElementById('divid').value = 'Change Text to This';

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

2 个答案:

答案 0 :(得分: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>

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

});

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

还要注意{{myVariable}}将数据注入到div中。当您更改输入中的值时,div文本也将更改。

答案 1 :(得分:1)

您必须将控制器绑定到您的标记并初始化您的Angular应用程序。

<div ng-app="myApp">
    <div id="divid" ng-controller="valueController">{{value}}</div>
</div>

然后您可以在控制器中简单地定义范围变量

myApp.controller("valueController", function($scope) {
    $scope.value = "Hi!";
});

最好在页面的HTML标记中使用ng-app指令

jsFiddle