Javascript – How to set the value of element in Angular.js

angularjsfrontendjavascript

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?

Best Solution

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.