fusionstrings
fusionstrings

Reputation: 1065

How to set ngModel inside ngRepeat within Angular JS custom directive

I am trying to create a directive where I am trying to generate forms dynamically, based on model. It seems somehow data-ng-model is not being set correctly in this scenario.

I am getting following output.

    <input type="{{ item.type }}" class="form-control" id="{{ item.id }}" data-ng-model="{{ item.model }}" placeholder="{{ item.label }}">

Whereas I am expecting following.

    <input type="text" class="form-control" id="role" data-ng-model="role.name" placeholder="Role Name">

One thing to note here is if I misspell or omit ng-model value it outputs correctly.

I've following code.

Template (cb-form-elements.html)

    <form class="form-horizontal" role="form" data-ng-submit="save()">
      <div class="form-group" data-ng-repeat="item in ngModel">
        <label for="{{ item.id }}" class="col-sm-2 control-label">{{ item.label }}</label>
        <div class="col-sm-6">
          <input type="{{ item.type }}" class="form-control" id="{{ item.id }}" placeholder="{{ item.label }}" data-ng-model="{{ item.model }}">
        </div>
      </div>

      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default">Create Role</button>
        </div>
      </div>
    </form>

Directive

    angular.module('secondarySalesApp')
      .directive('cbFormElements', function () {
        return {
          templateUrl: '/views/partials/cb-form-elements.html',
          restrict: 'EA',
            require: '^ngModel',
            scope: {
              ngModel: '='
            }
        };
      });

Controller

    angular.module('secondarySalesApp')
      .controller('RoleCtrl', function ($scope, Restangular) {
        $scope.roles = Restangular.all('roles').getList().$object;

        $scope.cbFormConfig = [{
            "label": "Role Name",
            'id': "role",
            'type': 'text',
            'model': 'role.name'
        }];

        $scope.save = function(){
            $scope.roles.post($scope.role);
        }
      });

Declaration

    <data-cb-form-elements data-ng-model="cbFormConfig"></data-cb-form-elements>

The same thing works if I move it into page from directive. Any help in this regard is appreciated.

Upvotes: 1

Views: 1027

Answers (1)

null
null

Reputation: 7926

The ng-model directive is not an interpolated directive; it will need a scope expression and not a string value.

Maybe this will help you: dynamic angular forms with febworms

Upvotes: 2

Related Questions