AngularJS表达式无法引用$rootScope变量

Angular version: 1.6.6
在HTML中想使用$rootScope中的变量时发现取不到,加上$root之后解决。

HTML表达式对应的JS变量
{{abc}} | $scope.abc {{$ctrl.abc}} | this.abc {{$root.abc}} | $rootScope.abc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.6.6/angular.min.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="myCtrl2 as ctrl2"></div>

<div ng-controller="myCtrl as ctrl">
<input type="text" ng-if="ctrl.name1" ng-model="ctrl.name1"><br>
<input type="text" ng-if="name2" ng-model="name2"><br>
<input type="text" ng-if="$root.name3" ng-model="name3"><br>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
this.name1 = "this.iMaeGoo";
$scope.name2= "$scope.iMaeGoo";
});

app.controller('myCtrl2', function($rootScope) {
$rootScope.name3= "$rootScope.iMaeGoo";
});
</script>

</body>
</html>

AngularJS表达式无法引用$rootScope变量

https://www.imaegoo.com/2019/ajs-rootscope-in-html/

作者

iMaeGoo

发布于

2019-04-01

更新于

2019-04-01

许可协议

CC BY 4.0

评论