Skip to content Skip to sidebar Skip to footer

How Do I Set The Value Of Element In Angular.js

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?

Solution 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:

<htmlng-app="myApp"><divng-controller="MyCtrl"><div>{{myVariable}}</div><inputtype="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.

Solution 2:

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

<divng-app="myApp"><divid="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

Post a Comment for "How Do I Set The Value Of Element In Angular.js"