Reputation: 273
I've created this very simple directive called <form-field>
, I'm trying to bind ng-model to that directive. I've broken down the example to the simplest usecase possible,
I've included the controller, and the directive with the HTML for the form it sits on. I've seen a lot of examples where require:ngModel
is used and then action takes place inside link:
but all these examples are just for either dom manipulation, or increments for instance that don't save a value
angular.module('taskApp', [])
.controller('taskController', function($scope) {
$scope.taskData = {};
$scope.save = function(taskData) {
$scope.taskData = angular.copy(taskData);
};
})
.directive('formField', function($timeout) {
var template = '<div class="form-group" ng-switch="element">' +
'<input ng-switch-when="input" ng-model="ngModel" name="{{field}}">' +
'<textarea ng-switch-when="textarea" ng-model="ngModel" name="{{field}}"></textarea>' +
'</div>';
return {
restrict: 'EA',
template: template,
replace: true,
scope: {
ngModel: '=',
field: '@',
live: '@',
element: '@'
},
link: function($scope, element, attr) {
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="taskApp" ng-controller="taskController">
<form name='taskForm' novalidate>
<form-field element='input' live='false' field="title" ng-model="taskData.title"></form-field>
<form-field element='textarea' live='false' field="notes" ng-model="taskData.notes"></form-field>
<button type="submit" ng-click="save(taskData)">save</button>
</form>
<br/>
<pre>{{taskData | json}}</pre>
</body>
Upvotes: 1
Views: 3658
Reputation: 883
ngModel
inside your directive still refers to the inner isolated scope. You can use $parent.ngModel
to access the outer model.
var template = '<div class="form-group" ng-switch="element">' +
'<input ng-switch-when="input" ng-model="$parent.ngModel" name="{{field}}">' +
'<textarea ng-switch-when="textarea" ng-model="$parent.ngModel" name="{{field}}"></textarea>' +
'</div>';
Upvotes: 3