angularjs中的$ ctrl是什么?什么时候在视图上使用$ ctrl vs $ scope? [英] What are $ctrl in angularjs? when to use $ctrl vs $scope on view?

查看:513
本文介绍了angularjs中的$ ctrl是什么?什么时候在视图上使用$ ctrl vs $ scope?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在视图上使用$ctrl

<b>Heroes</b><br>
<hero-detail ng-repeat="hero in $ctrl.list" 
             hero="hero" 
             on-delete="$ctrl.deleteHero(hero)" 
             on-update="$ctrl.updateHero(hero, prop, value)">
</hero-detail>

何时使用$ctrl和何时使用$scope与视图进行交互?

When to use $ctrl and when to use $scope for interacting with view?

https://docs.angularjs.org/guide/component

推荐答案

在视图中,您可以将别名绑定到控制器,从而轻松引用$scope变量. 当您嵌套controllers and you dont want to reference something from a different controller. since $ scope`遵循分层数据结构时,这很有用.

in views you can bind an alias to your controller making it easy to reference $scope variables. this is usefull when you nest controllers and you dont want to reference something from a different controller. since$scope` follows hierarchial data structure.

因此,为了确定控制器的范围,可以使用此语法.

so in order to scope your controller you can use this syntax.

例如,有两个控制器,两个控制器都具有相同的变量名称",您可以执行以下操作:

For example, having two controllers, both with the same a variable 'name', You can do this:

<body ng-controller="ParentCtrl as ptr">
<input ng-model="name" /> {{ptr.name}}

<div ng-controller="ChildCtrl as chl">
    <input ng-model="name" /> {{chl.name}} - {{ptr.name}}
</div>

这使得引用范围变量变得容易.

this makes it easy to reference the scope variables.

<b>Heroes</b><br>
<hero-detail ng-repeat="hero in $ctrl.list" 
             hero="hero" 
             on-delete="$ctrl.deleteHero(hero)" 
             on-update="$ctrl.updateHero(hero, prop, value)">
</hero-detail>

如果使用的是components,则在angulajs1.5后面的角中,其默认别名为$ctrl,当然您可以覆盖它.

after angulajs1.5 in angular if you are using components its default alias is $ctrl and ofcourse you can override it.

这篇关于angularjs中的$ ctrl是什么?什么时候在视图上使用$ ctrl vs $ scope?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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