简体   繁体   English

创建使用ng-model并具有唯一作用域的指令

[英]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. 范围:true在这种情况下显然行不通。 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. 这篇文章AngularJS-创建使用ng-model的指令对我有很大的帮助,但是我不知道最后一个范围问题。

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. 您的问题是将各个字段与各个ng模型绑定在一起。 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;
    }
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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