How do I set the value of element in Angular.js(如何在 Angular.js 中设置元素的值)
问题描述
为什么我不能在 Angular.js 中这样做:
Why can't I do this in Angular.js:
document.getElementById('divid').value = 'Change Text to This';
什么是正确"(Angular)的做法?
And what is the "right" (Angular) way of doing it?
推荐答案
在 Angular 中,您使用 ng-model
指令来创建模型之间的双向数据绑定(即 JS变量)和视图(即<div>
).基本上,这意味着无论何时您更改视图中的数据(例如,通过输入),更改都会反映在您的 JS 变量中.见下文:
In Angular you use the ng-model
directive 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:
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"作为初始值.对输入的任何进一步更改都将覆盖此变量的值.
Here, myVariable will have "initialValue" as an initial value. Any further changes to the input will overwrite the value of this variable.
还要注意 {{myVariable}}
将变量数据注入到您的 div 中.当您更改输入中的值时,div 文本也将更改.
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.
这篇关于如何在 Angular.js 中设置元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Angular.js 中设置元素的值


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06