Angular.js "Controller as ..." + $scope.$on

Angular.js "Controller as ..." + $scope.$on

如果我想在 Angular 中使用 "Controller as ..." 语法,我应该如何处理需要放入控制器中的 $scope.$on(...) 之类的东西?

我觉得我可以用下面所示的其他方式来做。 在这里,为了让 $scope.$on 工作,我将 "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); }
}]);

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>

据我所知,如果你想要$scope watchers/methods,你需要注入$scope。 ControllerAs 只是语法糖,可以让您更清楚地看到嵌套控制器的结构。

可以简化代码的三个想法。

  1. 使用 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);
    }
    
  2. 将整个 whereamINow 变量放入 app 的初始化中 .运行() (在配置之前)是有意义的,因为我假设它是一个全局变量,你不需要为它使用 $scope watcher/method。

  3. 另一种选择是使用工厂来使更改持久化,因此您只需创建一个保存当前活动路径的位置工厂。

好吧,我想人们也会这样做,就像这个问题一样:

Replace $scope with "'controller' as" syntax

注入 $scope 并且您的控制器可以通过您命名的任何内容访问

EG:

$stateProvider
  .state('my-state', {
    ...
    controller: 'MyCtrl',
    controllerAs: 'ctrl',
    ...
  });



.controller('MyCtrl', function($scope) {
  var $this = this;
  $scope.$on('ctrl.data', function(new, old) {
    // whatevs
  });
  $timeout(function() {
    $this.data = 'changed';
  }, 1000);
});