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

时间:2015-02-13 10:15:39

标签: angularjs angularjs-scope

如果我想将"控制器用作......"在Angular中的语法,我应该如何处理$ scope($)这样的东西,我需要把它放在控制器里面?

我得到一个印象,我可以采取其他方式,如下所示。 在这里,为了获得$ scope。$ on on bind i"这个"到回调函数。我试图在#34;这个"上调用$ 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>

3 个答案:

答案 0 :(得分:7)

据我所知,如果你想要$ scope观察者/方法,你需要注入$ 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又名.run()(在配置之前)的初始化中,因为我认为它是一个全局变量,你不需要使用$ scope观察者/方法它

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

答案 1 :(得分:0)

注入def redfrac gcd = @numer.gcd(@denom) if @denom != 0 rednumer = @numer/gcd reddenom = @denom/gcd if reddenom == 1 puts "#{rednumer}" else puts "#{rednumer}/#{reddenom}" end else puts "Cannot divide by 0" end end ,您可以通过任何名称来访问您的控制器

EG:

$scope

答案 2 :(得分:-2)

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

Replace $scope with "'controller' as" syntax