如何传递ng模型对象而不是指令内部的值

How pass a ng-model object instead of a value inside of a directive?

本文关键字:指令 内部 何传递 ng 模型 对象      更新时间:2023-09-26

我制作了一个输入指令,以在多个表单中使用它,所以我需要在提交表单时传递一个ng模型对象,而不是指令中的值。

这是代码

HTML:

<form name="formo" novalidate ng-submit="saveOrganization(org)">
....
      <responsible-select model="org.collaborators" show="1" id="id" adding="0" ></responsible-select>
....
</form>

指令:

angular.module('app').
   directive('responsibleSelect', function() {
    return {
      restrict: 'E',
      scope: {
        model :"=",
        show : '=',
        id : '=',
       adding : '='
      },
     controller: 'findCollabOrResCtrl',
     template: '<ui-select ng-model="model" reset-search-input="true"     tagging="tagTransform" multiple theme="bootstrap">'+
               '<ui-select-match placeholder="Escribe los emails de los colaboradores del área" >'+
              '{{$item.email}}'+
              '</ui-select-match>'+
              '<ui-select-choices refresh="refreshCollaborator($select.search,{{ show }},{{ id }},{{ adding }} )"refresh-delay="0" repeat="collaborator.email as   collaborator in collaborators">'+
             '{{collaborator.email}} '+
             '</ui-select-choices>'+
             '</ui-select>'
};
});

输出html:

<responsible-select model="org.collaborators" show="1" id="1" adding="0" class="ng-isolate-scope">
       <div ng-model="model" >...</div>
</responsible-select>

我需要这个输出:

<responsible-select model="org.collaborators" show="1" id="1" adding="0" class="ng-isolate-scope">
     <div ng-model="org.collaborators" >...</div>
</responsible-select>

这可能吗?

对指令使用"require"。

angular.module('app').
   directive('responsibleSelect', function() {
    return {
      restrict: 'E',
      require: 'ngModel'
      scope: {
        model :"=",
        show : '=',
        id : '=',
       adding : '='
      },
     controller: 'findCollabOrResCtrl',
     template: '<ui-select ng-model="model" reset-search-input="true"     tagging="tagTransform" multiple theme="bootstrap">'+
               '<ui-select-match placeholder="Escribe los emails de los colaboradores del área" >'+
              '{{$item.email}}'+
              '</ui-select-match>'+
              '<ui-select-choices refresh="refreshCollaborator($select.search,{{ show }},{{ id }},{{ adding }} )"refresh-delay="0" repeat="collaborator.email as   collaborator in collaborators">'+
             '{{collaborator.email}} '+
             '</ui-select-choices>'+
             '</ui-select>'
    };
});

此外,在控制器中定义paramethers。第四个参数将是ngModelCtrl,它是ngModel指令的控制器,您可以在其中获取值。

您需要定义"链接"函数来接受ngModel的控制器。

link: function ($scope, $element, attrs, ngModelCtrl)

并在链接函数中获取值并传递给指令的控制器。

如果ngModel的要求是可选的,例如您可以不使用它-使用"?ngModel’。