realph realph - 5 months ago 19
AngularJS Question

Angular: Evaluate Expression Passed into Component Attribute

How can I pass in the value of an Angular expression to a component's attribute? I'm getting the value back from an 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">


For some reason it's not evaluating
name
and it's logging
undefined
in the console.

Is there a way around this so it logs
Tom
inside the controller?

Any help is appreciated. Thanks in advance!

I've setup a jsFiddle here

Answer

& is for expressions, and @ is for interpolated strings, so try using

firstName: '&'

and then this.firstName() should evaluate the expression passed in.

Also, firstName is not guaranteed to have been initialized until $onInit, so if you do

bindings: {
    firstName: '&'
},
controller: function() {
    this.$onInit = function() {
        console.log(this.firstName());
    }
}

you should get your expected result.

For reference: 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



Edit:

After the extra information you provided, you should probably use a one-way binding (<) instead for this case, because it appears you are just passing in a single value (instead of an expression), and then you can detect changes in $onChanges. I forked your jsfiddle to show a potential solution: http://jsfiddle.net/35xzeo94/.