简体   繁体   中英

How same variable is used for ng-bind and ng-model

I am exploring AngularJS1 and found something strange, please help me to find how name is working for both ng-bind and ng-model here.

Output is coming as : John Doe but it is working for same variable name with bind and model there it is confusing me.Please help me to understand.

    <div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="name">
    <h1>{{name}}</h1><br>
    <p ng-bind="name"></p>
    </div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
</script>

They are all the same variable. You have $scope.name and you're telling ng-bind and ng-model to use $scope.name ;

ng-model="name" <-- Angular looks on the scope object for a property called name. If it's there it uses it, if it's not, it'll create it.

ng-bind="name" <-- Angular looks on the scope for a property called name. Then uses that value.

Angular created a scope object for the div with ng-controller

<div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="name">
    <h1>{{name}}</h1><br>
    <p ng-bind="name"></p>
</div>

All directives with-in that div's hierarchy can access the scope object. If you Google "Understanding Angular scopes" or something similar you'll get a lot of articles on it.

http://blog.carbonfive.com/2014/02/11/angularjs-scopes-an-introduction/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM