如果我想在 Angular 中使用“Controller as ...”语法,我应该如何处理需要放入 Controller 中的 $scope.$on(...) 之类的东西?
我得到的印象是,除了下面显示的方法之外,我还可以通过其他方式做到这一点。
在这里,为了让 $scope.$on 工作,我将“this”绑定(bind)到回调函数。我试图在 Controller 内的“this”上调用 $on,但它没有用。
你能在这里给我一个提示,或者如果我完全搞砸了,你能给我指出一些正确的方法吗?谢谢。
主.js:
angular.module('ramaApp')
.controller('MainCtrl', ['$scope', '$location', function ($scope, $location) {
this.whereAmINow = 'INDEX';
$scope.$on('$locationChangeStart', function(event) {
this.whereAmINow = $location.path();
}.bind(this));
this.jumpTo = function(where) { $location.path(where); }
}]);
索引.html:
<div ng-controller="MainCtrl as main">
<p>I am seeing the slide named: {{ main.whereAmINow }}</p>
<div ng-click="main.jumpTo('/slide1')">Slide 1</div>
<div ng-click="main.jumpTo('/slide2')">Slide 2</div>
<div ng-click="main.jumpTo('/slide3')">Slide 3</div>
</div>
最佳答案
据我所知,如果你想要 $scope 观察者/方法,你需要注入(inject) $scope。 ControllerAs 只是语法糖,可以让您更清楚地看到嵌套 Controller 的结构。
三个想法虽然可以简化你的代码。
var vm = this;
vm.whereAmINow = "/";
$scope.$on('$locationChangeStart', function(event) {
vm.whereAmINow = $location.path();
});
vm.jumpTo = function(where) {
$location.path(where);
}
关于angularjs - Angular.js "Controller as ..."+ $scope.$on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28497208/