AnjularJS中$scope和$rootScope的区别小结

2025-05-07 04:33:25
推荐回答(1个)
回答1:

一句话总结:
$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标签内容



我是全局变量language: {{ language}}