簡體   English   中英

創建使用ng-model並具有唯一作用域的指令

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

編輯-創建了一個柱塞

我正在嘗試制作一個自定義指令,以將其重復用於所有輸入。 每個輸入都會有不同的選項,具體取決於登錄的用戶(必需,隱藏等),因此我認為類似的方法會很完美。

我基本上是這樣工作的..

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

因此,在我添加第二個輸入並且共享上一個輸入的選項范圍之前,此方法一直有效。 范圍:true在這種情況下顯然行不通。 我需要每個自定義輸入來保留其自己的選項。 也許我只是想解決所有這些錯誤。

這篇文章AngularJS-創建使用ng-model的指令對我有很大的幫助,但是我不知道最后一個范圍問題。

您需要為選項設置一個隔離范圍,因此您的指令應如下所示:

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

現在,您的自定義輸入將具有自己的范圍

更新

更新的小提琴

您的問題是將各個字段與各個ng模型綁定在一起。 現在,隨心所欲的人會更新您想要的東西。 指令顯示在我使用的下方

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