I want to use the ng-model attribute in a custom element. The problem is, that I need to set the ng-model with an expression:
ng-model=\"{{anyVariable}}\"
I couldn't find a way to pass an expression to ng-model
within the directive template.
Following solution creates an isolated model within the directive and directive controller
dynamically creates the property name in main controller model object and watches the isolated model to pass updates to main model:
app.directive("textfield", function() {
return {
restrict: "E",
scope: {},
replace: true,
controller:function($scope,$attrs) {
$scope.x=$attrs;
$scope.$watch('directiveModel',function(){
$scope.$parent.myModel[$attrs.name]=$scope.directiveModel;
}) ;
$scope.directiveModel=$attrs.value;
},
template: buildFormTemplate('<input ng-model="directiveModel" id="{{x.id}}" type="text" name="{{x.name}}" value="{{x.value}}" />');
};
});
Plunkr Demo
Try a version of this:
.directive('myDir', function() {
return {
restrict: 'EA',
scope: {
YYY: '=ngModel'
},
require: 'ngModel',
replace: true,
template: '<input ng-model="YYY" />'
};
});