访问组件控制器中的角度分量参数

时间:2017-01-06 21:13:20

标签: javascript angularjs components angular-components

我在访问组件控制器中的组件参数时遇到问题。

(function() {
'use strict';

angular.module('myapp')
    .component('myComponent', {
        bindings: {
            name: '='
        },
        template: `<div>{{$ctrl.name}}</div>`,
        controller: function () {
            console.log(this.name); //displays undefined
        }
    });
}());

<my-component name="'mytest'"></my-component>

这输出&#34; mytest&#34;在页面上,模板内的{{$ ctrl.name}}确实有效。但是,我得到了未定义的&#39;当我尝试console.log控制器中的变量时。

由于

1 个答案:

答案 0 :(得分:0)

我能够通过向组件控制器添加$ doCheck挂钩来解决这个问题

angular.module('myapp')
    .component('myComponent', {
        bindings: {
            name: '='
        },
        template: `<div>{{$ctrl.name}}</div>`,
        controller: function () {
            console.log(this.name); //displays undefined

            this.$doCheck = function() {
                console.log(this.name); //works
            };
        }
    });
}());
相关问题