访问组件控制器中的绑定变量

时间:2016-06-23 20:26:15

标签: javascript angularjs binding components

我正在尝试console.log myobject,但我一直都未定义。我尝试使用$ scope.watch和$ attrs。$ observe。有人能告诉我我做错了什么。

这是html

<my-component some-data="$ctrl.data"></my-component>

这是组件和控制器

module.component('myComponent', {
bindings: {
  needThisStuff: '<someData'
},
controller: Ctrl,
templateUrl:
  requirejs.toUrl('path/to/templ.html')
 });

function Ctrl(){
var self = this;
console.log(self.needThisStuff);
}

如何使用$ watch或$ observe或其他任何东西访问needThisStuff,我使用的是angular 1.5

1 个答案:

答案 0 :(得分:2)

我很确定该对象未定义,因为只要组件加载,console.log就会触发。数据尚未返回,因此仍为undefined

作为测试方法的基本方法,您可以将您的console.log包装在$timeout中进行测试。

要解决此问题,使用角度组件生命周期挂钩。将您的Ctrl更改为以下内容:

function Ctrl {
    var self = this;
    this.$onChanges = function(changesObj) {
       console.log(changesObj.needThisStuff);
    }
}
每当更新单向绑定时都会调用

$onChanges,在这种情况下,这是needThisStuff变量。