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

2019-07-19 13:28发布

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?

2条回答
贪生不怕死
2楼-- · 2019-07-19 14:05

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

查看更多
放荡不羁爱自由
3楼-- · 2019-07-19 14:27

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.

查看更多
登录 后发表回答