简体   繁体   中英

Create a directive that uses ng-model and has unique scope

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.

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;
    }
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM