在使用$范围的方法ControllerAs语法 [英] ControllerAs Syntax when using $scope methods

查看:75
本文介绍了在使用$范围的方法ControllerAs语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现AngularJS controllerAs 语法1.3

我开始我的函数声明如下所示:

 函数(){
    VAR myCtrl =这一点;
    myCtrl.foo = foo的; //工作正常
    myCtrl在$(富,吧)。 //失败,说myCtrl。$上不是一个函数
}


解决方案

$范围 myCtrl 标识符AREN Ť互换。 控制器是在1.2引入并试图修复从 $范围,从范围原型的不良影响遭受的经​​验(它至少部分语法糖继承)。

 <机身NG控制器=MyCtrl为myCtrl>
...
app.controller('MyCtrl',函数(){
  ...
});

是相同的

 <机身NG控制器=MyCtrl>
...
app.controller('MyCtrl',函数($范围){
  $ scope.myCtrl =这一点;
  ...
});

这并未消除范围的需要,但引入了有用的模式,在控制器(请注意,你不需要在前例如注入 $范围,除非你需要 $范围。$关于等在那里)。

您可以很容易地看到自己通过登录这两个 $范围 myCtrl

I'm trying to implement controllerAs syntax in AngularJS 1.3

I'm starting my function declarations like so:

function() {
    var myCtrl = this;
    myCtrl.foo = foo; // works fine
    myCtrl.$on("foo", bar); // fails, says myCtrl.$on is not a function
}

解决方案

$scope and myCtrl identifier aren't interchangeable. 'Controller as' is a syntactic sugar that was introduced in 1.2 and tried to fix the experience from $scope (at least the part of it that suffered from undesirable effects of scope prototypal inheritance).

<body ng-controller="MyCtrl as myCtrl">
...
app.controller('MyCtrl', function () {
  ...
});

is identical to

<body ng-controller="MyCtrl">
...
app.controller('MyCtrl', function ($scope) {
  $scope.myCtrl = this;
  ...
});

It doesn't eliminate the need for scope but introduces useful pattern into the controller (note that you don't need to inject $scope in the former example, unless you need $scope.$on, etc. there).

You can easily see it by yourself by logging both $scope and myCtrl.

这篇关于在使用$范围的方法ControllerAs语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆