The difference between the ng model and the angular expression is {{}}

{{}} works fine, but the ng model is not there.

I am using the following html -

<body ng-app="crud"> Gray input fields will not be visible. <div ng-controller="ctrl"> <input type="text" value="sdf" ng-model="asdf"/> <h1 ng-model="asdf"></h1> <!-- this doesn't work--> <h1>{{asdf}}</h1> <!-- this work--> </div> </div> </body> 

asdf is defined in this js application like this

  var app = angular.module("crud", []); app.controller("ctrl", ['$scope', function($scope) { $scope.asdf="ankur"; }]); 

Can someone explain why this is so?

+5
source share
5 answers

The ng-model directive should be used in input fields, such as input, choice for two-way data binding, and receiving input from the user.

As a one-way data binding expression, {{}} or the ng-bind directive is used to output data in a view.

 var app = angular.module("crud", []); app.controller("ctrl", ['$scope', function($scope) { $scope.asdf="ankur"; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="crud"> Gray input fields will not be visible. <div ng-controller="ctrl"> <input type="text" value="sdf" ng-model="asdf"/> <h1 ng-bind="asdf"></h1> <h1>{{asdf}}</h1> </div> </div> 
+5
source

Use ng-bind to display, not ng-model .

 <h1 ng-bind="asdf"></h1> 

You want to use ng-model only when binding to the element that will edit the variable, for example a text field.

0
source

From the documentation :

The ngModel directive associates input , select , textarea (or custom form control) with a property in scope using the NgModelController , which is created and displayed by this directive.

You are trying to use it on <h1> . Use ng-bind instead.

0
source

According to the document

 the ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. 

therefore you will not use it to display H1

In parentheses, they will be dirty checked and updated in every $ digest, even if this is not necessary. So it is slower. Plus thez may appear while your angularjs is loading.

0
source

ng-model . This directive associates AngularJS application data values ​​with HTML input controls.

{{}} This is a print only use. you can put an expression just like {{2 * 2}}, it prints 4

Refer to this basic learning syntax https://angularjs.org/

0
source

All Articles