AngularJs Scrope

来源:互联网 发布:cdr文件查看器 mac 编辑:程序博客网 时间:2024/05/16 07:31

The scrope is the binding part between the HTML (view) and theJavascript (controller)

The scrope is an object with the available properties and methods

The scrope is avaible for both the view and the controller

<1>How to use the Scope

pass the $scope as the function's argument, and then, you must start all the states with$scrope

Example

Properties made in the controller, can be referred to in the view:

<div ng-app="myApp" ng-controller="myCtrl">

<h1>{{carname}}</h1>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl'function($scope) {
    $scope.carname = "Volvo";
});
</script>
Try it Yourself »

<2>understand the Scrope

Considering AngularJs application cnsist of three elemenets:

1.View, which is HTML

2. Model, whilch is the data avaible for the currewnt view

3.Controler, whilch is the Javascript function thatmakes/changes/removes/controles the data

<3>Know Your Scrope

<4>Root Scope

1.All applications have a  $rootScope whilch is the scope created on the HTML element that contains the ng-app directive

2.Available in the entire application.

3.When current  scope have the same name with the rootscope, the current have the higher priority

Example

A variable named "color" exists in both the controller's scope and in the rootScope:

<body ng-app="myApp">

<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>

<div ng-controller="myCtrl">
    <p>The scope of the controller's favorite color:</p>
    <h1>{{color}}</h1>
</div>

<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1>

<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
    $rootScope.color = 'blue';
});
app.controller('myCtrl'function($scope) {
    $scope.color = "red";
});
</script>
</body>
Try it Yourself »
the rootscope exist only when we define it,  that is to say, we have two object::$scope and the $rootscope,, and we use $rootscope by app.run(),
and we use scope by app.controller(), there have a little difference

0 0
原创粉丝点击