我使用Angular组件(来自this的第一个例子)。当我在组件中绑定对象时,它可以在模板中访问,但不在控制器中。
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(这里有效):
<span>Name: {{ctrl.hero.name}}</span>
错误:
ReferenceError:未定义英雄
答案 0 :(得分:8)
bindings
个HeroDetailController
内容中的this
值将为function HeroDetailController() {
var ctrl = this;
console.log("Here I want to use hero.name: ");
console.log(ctrl.hero);
}
$onInit
虽然上面不起作用。因为它不会在第一个摘要周期中将初始绑定传递给组件。
要获取值,您可以在组件上使用function HeroDetailController() {
var ctrl = this;
console.log("Here I want to use hero.name: ");
ctrl.$onInit = function(){
console.log(ctrl.hero);
}
}
生命周期值。
$onInit
即使您可以在没有$compileProvider
的情况下直接获得值。同样,您必须更改.config(function($compileProvider){
$compileProvider.preAssignBindingsEnabled(true)
});
配置,如下所示。(已在1.6 +中引入)
nextRow
注意:理想情况下,您不应该在您的应用程序中强制执行上述设置,我只是先进行演示。