时间:2020-12-05 11:53:59 | 栏目:AngularJS | 点击:次
一句话总结:
$rootScope针对全局的作用域生效
$scope只针对当前的controller作用域生效
用下面的例子来证明上述的说法:
定义一个模块名为myApp
var myApp = angular.module('myApp', []);
创建oneController和twoController这两个controller
oneController传入$scope和$rootScope
myApp.controller('oneController', ['$scope', '$rootScope', function ($scope, $rootScope) { // 局部的变量,只有在oneController中才会显示 $scope.one_language = 'Python'; // 全局的变量,都可以调用 $rootScope.language = 'Go'; }]);
twoController只传入$scope
myApp.controller('twoController', ['$scope', function ($scope) { // 局部的变量,只有在twoController中才会显示 $scope.two_language = 'Java'; }]);
HTML标签内容
<span ng-app="myApp"> <style> div{margin-top: 15px;border: 2px solid rebeccapurple;width: 400px;} </style> <div> <h3>我是全局变量language: {{ language}}</h3> </div> <div ng-controller="oneController"> <h3>我是one_language局部变量: {{ one_language}}</h3> </div> <div ng-controller="twoController"> <h1>twoController</h1> <h3>我是two_language局部变量: {{ two_language }}</h3> <h3>我是one_language局部变量: {{ one_language}}</h3> <h3>我是全局变量language: {{ language }}</h3> </div> </span>
显示的结果
总结