Reputation: 4671
I'm trying to use AngularJs 1.5 components but everytime I declare bindings
I keep getting this error:
Expression 'undefined' in attribute 'message' used with directive 'homeComp' is non-assignable!
I'm trying a simple component, just to learn it, this is the code:
var component = {
bindings: {
message: '='
},
controllerAs: 'vm',
controller: function MainController() {
this.message = 'Welcome to my component';
function debug() {
this.message = 'This message changed';
}
this.debug = debug;
},
template: [
'Message: {{ vm.message }}<br />',
'<button ng-click="vm.debug()">Change message</button>'
].join(``)
};
You can see the error here: http://plnkr.co/edit/uutk5kxOVpa5eLfjoa8U?p=preview
What is wrong with the code? Or what is causing this error? If I remove the bindings, the error doesn't appear and I can change the message.
Upvotes: 1
Views: 1244
Reputation: 22323
It is not necessary to use the binding
option in your component if the property being referenced is only used by the component itself.
By using binding
with the =
for the message
property, you are specifically telling the directive that the parameter is a two way binding, meaning that it will be set in the parent HTML, and that changes to the message
property should be written back to the HTML. Because the <home-comp>
tag does not have a message
property, the HTML is not assignable (cannot be written back to).
There are three ways to fix this error:
<home-comp message="default message">
requirement and always provide the property in the HTML.binding
to be optional, by using message: '=?'
. plunkrmessage
property from the binding
completely, if it is not intended to be set from the HTML.Upvotes: 5
Reputation: 11308
It's because you've defined message as a 2 way binding, but your html doesn't provide anything to bind to.
This line:
<home-comp></home-comp>
should be
<home-comp message='myMessageVariable'></home-comp>
And you need to declare myMessageVariable somewhere in the scope.
Upvotes: 2