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

标签 angularjs angularjs-scope

如果我想在 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,以摆脱绑定(bind)(this)。
    var vm = this;
    vm.whereAmINow = "/";
    
    $scope.$on('$locationChangeStart', function(event) {
        vm.whereAmINow = $location.path();
    });
    
    vm.jumpTo = function(where) {
        $location.path(where);
    }
    
  • 将整个 whereamINow 变量放入 app aka .run() (在配置之前)的初始化中是有意义的,因为我认为它是一个全局变量,并且您不需要为它使用 $scope 观察程序/方法。
  • 另一种选择是使用工厂来使更改保持不变,因此您只需创建一个保存当前事件路径的位置工厂。
  • 关于angularjs - Angular.js "Controller as ..."+ $scope.$on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28497208/

    相关文章:

    javascript - ng-click 没有在 angularjs 中触发?

    javascript - 将对象数组添加到 Angular 范围对象中 -- TypeError

    javascript - Angular Js 中的过滤器

    javascript - 即使使用类似 $scope.user={pwd1 :'' } 的 $watch 也无法在 Modal 中工作

    angularjs - AngularJS 中的范围未更新

    angularjs - 使用 ng-if 作为 ng-repeat 内部的开关?

    angularjs - 有没有AngularJS方式可以在我的 Controller 中按下某个键来调用例程?

    javascript - Angular js 指令属性未附加到指令范围

    javascript - 为什么这个 Angular Directive(指令)在加载之前会滞后?

    javascript - 使用 HTML 5 和 angularJs 只允许整数(并限制小数)的最快方法是什么