Gre*_*reg 13 angularjs angularjs-scope
如果我想在Angular中使用"Controller as ..."语法,我应该如何处理$ scope($)这样的东西,我需要放入控制器?
我得到一个印象,我可以做一些其他方式,如下所示.在这里,要获得$ scope.$ on work i将"this"绑定到回调函数.我试图在控制器内的"this"上调用$ on但它没有用.
你能不能在这里给我一个提示,或者如果我完全搞砸了,你能指点我做一些正确的方法吗?谢谢.
main.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); }
}]);
Run Code Online (Sandbox Code Playgroud)
index.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>
Run Code Online (Sandbox Code Playgroud)
据我所知,如果你想要$ scope观察者/方法,你需要注入$ scope.ControllerAs只是语法糖,可以更清楚地看到嵌套控制器的结构.
虽然有三个想法可以简化您的代码.
使用var vm = this,以摆脱bind(this).
var vm = this;
vm.whereAmINow = "/";
$scope.$on('$locationChangeStart', function(event) {
vm.whereAmINow = $location.path();
});
vm.jumpTo = function(where) {
$location.path(where);
}
Run Code Online (Sandbox Code Playgroud)整个whereamINow变量有意义将它放入app的初始化.run()(在配置之前)因为我认为它是一个全局变量,你不需要使用$ scope观察者/方法.
另一种选择是使用工厂来保持更改,因此您只需创建一个保存当前活动路径的位置工厂.