Andreas Arnold
Andreas Arnold

Reputation: 545

Form input in a directive with isolated scope: How to set ngModel to the correct scope?

I try to display a list of different questions. Each question has its own form inputs. So I wrote a directive that sets up these form inputs. But setting ngModel in the input tags won't update the isolated scope.

What I currently have tried:

<body ng-app="stepModule" ng-controller="ChallengeCtrl">
  <div question step="step"></div>
</body>

And the JS:

angular.module('stepModule', [])
.directive('question', function() {
  return {
    restrict: 'A',
    replace: true,
    scope: {
      step: '='
    },
    template: "<form ng-submit=\"submit()\">\n  
               Step = {{step}}\n
               <label for=\"question\">Question</label>\n  
               <input ngModel=\"step.question\" ng-required=\"true\" name=\"question\" />\n
               <label for=\"answer\">Answer</label>\n  
               <input ngModel=\"step.answer\" ng-required=\"true\" name=\"answer\" />\n
               <input type=\"submit\" value=\"Save (extract out, should save automatically)\" />\n
               </form>",
    controller: [
      "$scope", "$element", "$attrs", function($scope, $element, $attrs) {
        $scope.submit = function() {
          console.log($scope.step.question);
          console.log($scope.step.answer);
        };
      }
    ]
  };
});

Here console.log will output the original contents of the $scope.step instead of the new values. Here a Plunker showing that behavior.

Is there a way to get ngModel to use the directives scope? Or am I just just missing something / abusing AngularJS (which wouldn't surprise me the least...)

Upvotes: 1

Views: 556

Answers (1)

noj
noj

Reputation: 6759

The attribute syntax for ngModel is ng-model, ie ng-model=\"step.answer\"

Upvotes: 2

Related Questions