0

EDIT - Created a Plunker

I'm trying to make a custom directive to be reused for all of my inputs. Each input would have different options depending on the logged in user (required, hidden, etc), so I thought something like this would be perfect.

I basically have it working like this..

{{username}}
 <custom-input name="username" ng-model="username"></custom-input>


app.directive('customInput', function ($compile) {
  return {
    restrict: 'E',
    templateUrl: '/app/shared/views/custom-input.html',
    replace: true,
    link: function ($scope, element, $attr) {
      var options = getFieldOptions($attr.name);
      $scope.options = options;
      var model = element.attr('ng-model');

      return $compile($('input', element).attr('ng-model', model))($scope);
  }
};
});

So this works until I add a second input and it shares the options scope from the last one. Scope: true obviously doesn't work in this situation. I need each custom input to keep its own options. Or maybe I'm just going about this all wrong.

This post AngularJS - Create a directive that uses ng-model has been a great help to me, but I can't figure out this last scope issue.

Community
  • 1
  • 1
Ricka
  • 247
  • 3
  • 11

1 Answers1

0

You need to have an isolated scope for options, so your directive should look like this:

app.directive('customInput', function ($compile) {
  return {
    restrict: 'E',
    templateUrl: '/app/shared/views/custom-input.html',
    replace: true,
    scope:{
      name:'='
    },
    link: function (scope, element, $attr) {
      var options = getFieldOptions(scope.name);
      scope.options = options;
      var model = element.attr('ng-model');

      return $compile($('input', element).attr('ng-model', model))(scope);
  }
};
});

Now your custom input will have its own scope

UPDATE

Updated fiddle

Your problem was to bind individual fields with individual ng-models. Now the plunker is updated with what you desire. and the directive is shown below what I used

app.directive('customInput', function ($compile) {
  return {
    restrict: 'E',
    template: '<div>{{options.Id}}<input ng-model="name"/></div>',
    replace: true,
    scope: {
     name:'=',
    },
    link: function ($scope, element, $attr) {
    var options = getFieldOptions($attr.name);
      $scope.options = options;
    }
  };
});
V31
  • 7,626
  • 3
  • 26
  • 44
  • Thanks for the reply, but as soon as I add the scope:{} my {{username}} binding stops working. – Ricka Jul 30 '14 at 15:27
  • added to include username...hope that helps @Ricka – V31 Jul 30 '14 at 15:34
  • As soon as I mess around with the scope at all..I appear to lose my two way binding. I'm new to angularjs, so I guess I'm just missing some concept. I created a plunker if you care to take a gander – Ricka Jul 30 '14 at 16:10
  • @Ricka: Updated the answer as per your plunker – V31 Jul 31 '14 at 05:27