kmassada kmassada - 6 months ago 37
AngularJS Question

angular directive with ng-model not binding

I've created this very simple directive called

, 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
is used and then action takes place inside
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 = {};
$ = 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>' +
return {
restrict: 'EA',
template: template,
replace: true,
scope: {
ngModel: '=',
field: '@',
live: '@',
element: '@'
link: function($scope, element, attr) {


<script src=""></script>
<script src=""></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>


<pre>{{taskData | json}}</pre>



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>' +