我正在尝试组合我的代码库并且已经遇到了这个问题。
当使用$ scopes和Controllers时,我会使用ng-init将服务器令牌传递给我的rest调用方法。尝试对组件执行相同操作无效。
的javascript
angular
.module('myApp', [])
.controller('mainCtrl', function() {
var self = this;
self.options = function() {
var o = {}
o.token = self.serverToken
return o;
}
self.restData = {
url: 'http://rest.url',
options: self.options()
}
})
.component('myComponent', {
bindings: {
restData: '<'
},
template: '<p>template, calls child components</p>',
controller: function(restService) {
this.callRestService = function() {
restService.get(this.restData.url, this.restData.options)
}
console.log(this.restData.url) // http://rest.url
console.log(this.restData.options) // {token: undefined}
}
})
HTML
<html ng-app="myApp">
<!-- head -->
<body ng-controller="mainCtrl as m" ng-init="m.serverToken='12345'">
<my-component rest-data="m.restData"></my-component>
</body>
</html>
如何将值传递给组件?
答案 0 :(得分:1)
问题是在实例化控制器之后执行ng-init。但是,您在构造控制器期间创建了restData对象,此时serverToken未定义。
在使用类似这样的东西调用ng-init之后,你可以构建你的restData对象:
.controller('mainCtrl', function() {
var self = this;
self.restData = {};
self.init = function(token) {
self.serverToken=token;
self.restData = {
url: 'http://rest.url',
options: {token:token}
};
};
})
然后,当restData发生更改时,您的组件可以执行某些操作。例如:
.component('myComponent', {
bindings: {
restData: '<'
},
template: '<p>template, calls child components</p>',
controller: function(restService) {
this.callRestService = function() {
restService.get(this.restData.url, this.restData.options)
}
this.$onChanges = function(changes) {
console.log(this.restData) // http://rest.url
console.log(this.restData.options) // {token: 12345}
this.callRestService();
}
}
});
HTML将更改为调用您的init方法:
<body ng-controller="mainCtrl as m" ng-init="m.init(12345)">
<my-component rest-data="m.restData"></my-component>
</body>