Angular:评估传递到组件属性中的表达式
Angular: Evaluate Expression Passed into Component Attribute
如何将 Angular 表达式的值传递给组件的属性?我正在从 API.
中取回值
app.controller.js
$http.get(apiUrl).then(function(resp) {
$scope.name = resp.data.name;
})
...
person.component.js
export const Person = {
templateUrl: 'person.html',
bindings: {
firstName: '@'
},
controller: function() {
console.log(this.firstName);
}
}
app.html
...
<person first-name="name">
出于某种原因,它没有评估 name
,而是在控制台中记录 undefined
。
是否有解决此问题的方法,以便它在控制器中记录 Tom
?
感谢任何帮助。提前致谢!
我已经设置了一个 jsFiddle here
&
用于表达式,@
用于内插字符串,因此请尝试使用
firstName: '&'
然后 this.firstName()
应该计算传入的表达式。
此外,firstName
不能保证在 $onInit
之前已经初始化,所以如果您这样做
bindings: {
firstName: '&'
},
controller: function() {
this.$onInit = function() {
console.log(this.firstName());
}
}
您应该会得到预期的结果。
供参考:https://docs.angularjs.org/guide/component
$onInit()
- Called on each controller after all the controllers on an element have been constructed and had their bindings initialized
编辑:
在您提供额外信息后,对于这种情况,您可能应该使用单向绑定 (<
),因为看起来您只是传递了一个值(而不是表达式) ,然后您可以检测 $onChanges
中的变化。我分叉了你的 jsfiddle 来展示一个潜在的解决方案:http://jsfiddle.net/35xzeo94/。
如何将 Angular 表达式的值传递给组件的属性?我正在从 API.
中取回值app.controller.js
$http.get(apiUrl).then(function(resp) {
$scope.name = resp.data.name;
})
...
person.component.js
export const Person = {
templateUrl: 'person.html',
bindings: {
firstName: '@'
},
controller: function() {
console.log(this.firstName);
}
}
app.html
...
<person first-name="name">
出于某种原因,它没有评估 name
,而是在控制台中记录 undefined
。
是否有解决此问题的方法,以便它在控制器中记录 Tom
?
感谢任何帮助。提前致谢!
我已经设置了一个 jsFiddle here
&
用于表达式,@
用于内插字符串,因此请尝试使用
firstName: '&'
然后 this.firstName()
应该计算传入的表达式。
此外,firstName
不能保证在 $onInit
之前已经初始化,所以如果您这样做
bindings: {
firstName: '&'
},
controller: function() {
this.$onInit = function() {
console.log(this.firstName());
}
}
您应该会得到预期的结果。
供参考:https://docs.angularjs.org/guide/component
$onInit()
- Called on each controller after all the controllers on an element have been constructed and had their bindings initialized
编辑:
在您提供额外信息后,对于这种情况,您可能应该使用单向绑定 (<
),因为看起来您只是传递了一个值(而不是表达式) ,然后您可以检测 $onChanges
中的变化。我分叉了你的 jsfiddle 来展示一个潜在的解决方案:http://jsfiddle.net/35xzeo94/。