angular js set使用$ on而不使用$ scope

时间:2016-02-19 21:53:28

标签: javascript angularjs

我在角度看到设置控制器有两种方式。 老:

app.controller('my_ctrl', ['$scope', function($scope){
  $scope.a = null;
}]);

和这一个:

app.controller('my_ctrl',function(){
      this.a = null;
});

现在我尝试使用$ on on listener和int他们使用$ scope的文档。我试着像这样使用它:

  

此。$上

但我有这个错误:

this.$on is not a function

我怎样才能以第二种方式使用$ on?

1 个答案:

答案 0 :(得分:3)

您使用$on的方式是在$scope变量本身而不是this指针上使用它。

试一试。

$scope.$on('listener', function() {})

所以对你的例子

app.controller('my_ctrl', function($scope) {
  $scope.$on('listener', function() {
    // do stuff on the event
  })
})