I'm trying to write tests for a directive, so I'm constructing it by hand with $compile
. (Yes, I know that I can use e2e tests for this, but in this case I want to test some DOM independent logic so I'm using the unit test approach.)
I have a field that I'm binding to with scope: {foo: '='}
. When I try to set it on the directive's scope, I get the following error:
Error: Non-assignable model expression: undefined (directive: foo)
at Error (<anonymous>)
at $get.parentSet (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:4146:25)
at Object.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:4160:23)
at Object.$get.Scope.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:7693:38)
at Object.$get.Scope.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:7894:24)
at SNAKE_CASE_REGEXP (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:930:13)
at Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:2788:25)
at bootstrap (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:928:12)
at angularInit (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:904:5)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:14397:5
Reproduced in this fiddle.
In your directive you have:
scope: {
bar: '='
}
This means it's going to look on the directive element (<div foo></div>
) for an attribute name "bar" and do a two-way databinding within your directive and the object specified for the attribute. So, first you need to add a bar
attribute, and then you need to have something set in your scope with the name of the value of the attribute. See http://jsfiddle.net/u4BTu/6/
Another possible cause of this error is neglecting to account for Angular's normalization of the attributes. For instance, if you have the following directive:
<my-directive parameter-one="foo" parameter_two="bar"></my-directive>
With this scope declaration:
scope: {
'parameter-one': '=',
parameter_two: '=',
}
You'll get this error. To correct, use the normalized versions for the scope declaration:
scope: {
parameterOne: '=',
parameterTwo: '=',
}