My question is very common one. I saw many different cases of people with similar question to mine, but I still does not have my answer.
[My goals]
I want to implement a standalone directive to encapsulate div consisting of label(span) and value(input). There are some specifics that worth mentioning here:
[My approach]
I am using the directive compile phase to manipulate the directive's HTML (mainly adding properties to directive's template HTML). In the pre-link phase I want manipulate the scope that directive is using in order to add the directive's placeholder to my desired scope and assign it some default value if needed. (I guess I can achieve that with ng-init instead of messing with the scopes, but i believe that is irrelevant to my question).
[What I did]
As I explained above I have a function (determinePlaceholderName()) that returns a string which is the exact value I want to assign to ngModel. For example:
$parent.$parent.$parent.placeHolderName
I want to assign that function to input's ng-model attribute assuming that Angular will treath it as an expression, evaluate it and produce what I expected. Here is how I assign the ng-model property:
compile: function(cElem, cAttrs) {
//Some non relevant code here ....
$(cElem[0]).find("div input").attr("ng-model", "determinePlaceholderName()");
}
Basically what I expect is this to be treated like:
$(cElem[0]).find("div input").attr("ng-model", "$parent.$parent.$parent.placeHolderName");
[About determinePlaceholderName()]
This function I define in the link function of my directive:
link: function ($scope) {
$scope.constructValuePlaceholderName = function() {
//Some logic here.
return result;
}
[My Problem]
And finally what my problem is.
Angular result in an error explaining to me that
<input ng-model="myFunc()">
is non-assignable expression as documented.
[My Question]
How can I dinamically set ngModel if function assignment is forbidden by Angular??
Thank you for your time!
I hope this is what you're looking for:
http://plnkr.co/edit/TojgLNx3TUbmszhfs8Ui?p=preview
Using isolated scope, you can pass the name of the model, and the directive itself is not aware of the scope the model actually sits on or its name, but is able to use it as is and give it to ngModel.
The plunker also provides alternatives in case you don't want to use isolate scope or want to use a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With