controllerAs跟ui-route
来源:4-4 移动端自适应

李行知
2017-12-25
我在看angularJS的哪个代码规范。有个疑问。
里面有一条是这样写的。
在控制器里面不要使用$scope
/* avoid */ function CustomerController($scope) { $scope.name = {}; $scope.sendMessage = function() { };}
而是要
/* recommended - but see next section */function CustomerController() { this.name = {}; this.sendMessage = function() { };
}
然后控制使用controllerAs
但是我去用的时候却失败了。
但是我新建一个html文件,这样写确可以成功
<body>
<div ng-controller="ngc as cc">
{{cc.name}}
</div>
<script>
(function () {
angular.module('app', []);
angular.module('app')
.controller('ngc', ngc);
/@ngInject/
function ngc() {
var _this = this;
this.name = "ss";
}
}())
</script>
</body>
这是为什么?怎么解决?
写回答
2回答
-
慕雪1613582
2017-12-27
this创建了独立作用域,而$scope默认是继承作用域,当然指令中也可以使用独立作用域。所以我在课程中用的$scope。
可以参考这篇文章
http://www.alloyteam.com/2015/04/angularjs-this-yu-scope/
00 -
李行知
提问者
2017-12-25
问题已经解决,但是还是不怎么懂这样用的好处在那里。感觉还要多很多的代码。
00
相似问题