I am creating a directive, in which i want to compare the value stored in a model (say "name" as model and it is having value "Angular")
to be stored in a variable.
I tried something like below,
var nameValue=name;
but it(nameValue) is not having the value "Angular"
Example:
app.directive('kmRadio', function() {
return{
restrict:'E',
compile: function(element,attrs) {
var model=ngModelName;
console.info(attrs.kmModel);
console.info("{{'+attrs.kmModel+'}}");
if(attrs.kmTitle==model) {
previewString="<input type="+"radio"+" checked>";
}
else {
previewString="<input type="+"radio"+">";
}
var htmlText=''+previewString+''+
element.replaceWith(htmlText);
}
}
})
Can anyone tell me how to retrieve the value stored in model(ng-model)
You can link attributes in the directive scope to the parent with the scope
attribute. A detailed explanation can be found here: What is the difference between '@' and '=' in directive scope in AngularJS?
In essence adding
return{
restrict:'E',
scope: {
kmModel: '=kmModel'
}
compile: function(element,attrs) {
var model=ngModelName;
console.info(attrs.kmModel);
console.info("{{'+attrs.kmModel+'}}");
if(attrs.kmTitle==model) {
previewString="<input type="+"radio"+" checked>";
}
else {
previewString="<input type="+"radio"+">";
}
var htmlText=''+previewString+''+
element.replaceWith(htmlText);
}
}
Would solve your problem.
You can simplify things a bit with ng-checked
, and a link function:
app.directive('kmRadio', function() {
return {
restrict: 'E',
scope: true,
replace: true,
template: "<input type='radio' ng-checked='title == model' />",
link: function(scope, element, attrs) {
scope.model = scope.$eval(attrs.kmModel);
scope.title = attrs.kmTitle;
console.info('attrs.kmModel: ', attrs.kmModel);
console.info('scope.$eval(attrs.kmModel):', scope.model);
}
}
})
Here is a working demo: http://plnkr.co/edit/owTLnPUbbZIhwUtfoivt?p=preview