您的位置:首页 > Web前端 > AngularJS

AngularJs Scrope

2016-04-03 22:33 489 查看
The scrope is the binding part between the HTML (view) and the
Javascript (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 that
makes/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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: