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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25079934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:53:54  来源:igfitidea点击:

How do I set the value of element in Angular.js

javascriptangularjsfrontend

提问by nelsonic

Why can't I do this in Angular.js:

为什么我不能在 Angular.js 中做到这一点:

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

And what is the "right" (Angular) way of doing it?

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

回答by ABucin

In Angular you use the ng-modeldirective in order to create a two-way data binding between your model (i.e. a JS variable) and the view (i.e. the <div>). Basically, this means that whenever you change the data in the view (through an input, for instance), the change will be reflected in your JS variable. See below:

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

HTML:

HTML:

<html ng-app="myApp">
    <div ng-controller="MyCtrl">
        <div>{{myVariable}}</div>
        <input type="text" ng-model="myVariable" />
    </div>
</html>

JS:

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

});

Here, myVariable will have "initialValue" as an initial value. Any further changes to the input will overwrite the value of this variable.

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

Also notice that {{myVariable}}injects the variable the data into your div. When you change the value in the input, the div text will be changed as well.

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

回答by Stefan

You'd have to bind a controller to your mark up and initialise your Angular app.

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

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

Then you can simply define a scope variable in your controller

然后你可以简单地在你的控制器中定义一个范围变量

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

It is considered best to use the ng-app directive in the HTML tag of the page

被认为最好在页面的 HTML 标签中使用 ng-app 指令

jsFiddle

js小提琴