AngularJS组件:在控制器中使用绑定对象 [英] AngularJS component: using binding object in controller
问题描述
我使用Angular组件(来自此的第一个示例)。当我在组件中绑定对象时,它可以在模板中访问,但不在控制器中。
I use Angular component (first example from this). When I binding object in component, it is accessible in template, but isn't in controller.
js:
function HeroDetailController() {
console.log("Here I want to use hero.name: ");
console.log(hero.name); // I want to use binding object in controller, but doesn't work
}
angular.module('heroApp').component('heroDetail', {
templateUrl: 'heroDetail.html',
controller: HeroDetailController,
controllerAs: 'ctrl',
bindings: {
hero: '='
}
});
html:
<hero-detail hero="ctrl.hero"></hero-detail>
模板html(这里有效):
template html (here it works):
<span>Name: {{ctrl.hero.name}}</span>
错误:
ReferenceError:未定义英雄
ReferenceError: hero is not defined
Plunker: https://plnkr.co/edit/U9CJLs6jgrlsZH6tUdr0
推荐答案
你将获取绑定
HeroDetailController
上下文的值此
You will get bindings
value inside HeroDetailController
context which is this
function HeroDetailController() {
var ctrl = this;
console.log("Here I want to use hero.name: ");
console.log(ctrl.hero);
}
虽然上面不起作用。因为它不会在第一个摘要周期中将初始绑定传递给组件。
Though above would not work. Because it would not pass initial binding to component on 1st digest cycle.
获取值可以使用 $ onInit
组件上的生命周期值。
For getting the value you could use $onInit
lifecycle value on component.
function HeroDetailController() {
var ctrl = this;
console.log("Here I want to use hero.name: ");
ctrl.$onInit = function(){
console.log(ctrl.hero);
}
}
即使你没有 $ onInit
也可以直接得到一个值。同样你需要更改 $ compileProvider
config,如下所示。(它已经在1.6 +中引入)
Even you could get a value directly without $onInit
. For the same you have to change $compileProvider
config like below.(it has been introduced in 1.6+)
.config(function($compileProvider){
$compileProvider.preAssignBindingsEnabled(true)
});
注意:理想情况下,您不应在申请中强制执行上述设置,我刚才给出了演示。
Note: Ideally you shouldn't enforce above setting in your application, I just gave it fore demonstration.
这篇关于AngularJS组件:在控制器中使用绑定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!