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

纵饮孤独 提交于 2019-12-11 02:43:44

问题


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

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

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


回答1:


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

});

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

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.




回答2:


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

<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

jsFiddle



来源:https://stackoverflow.com/questions/25079934/how-do-i-set-the-value-of-element-in-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!