如何使ng中的每个指令重复以共享同一个ng模型

How to make each directive inside ng-repeat to share the same ng-model?

本文关键字:ng 共享 同一个 模型 何使 指令      更新时间:2023-09-26

这是jsfiddle

JS文件

var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function ($scope) {
     $scope.foo = "I'm foo!";
    $scope.test = [1,2,3,5,6,7];
    $scope.$watch('foo', function(){
     console.log($scope.foo);
    });
});
myApp.directive('myDirective', function () {
    return {
        restrict: 'AE',
        template: '<div><input type="text" ng-model="ngModel" /></div>',
        replace: true,
        scope: {
            ngModel : '=',
        },
        link: function(scope){
          scope.ngModel = 'test';
        }
    };
});

HTML文件

<div ng-app="MyApp" ng-controller="MyCtrl">
    {{foo}}<br />
   <div ng-repeat="k in test">
       <my-directive ng-model="foo" />
   </div>
</div>

我想让每个my-directive共享相同的ng-model foo,我们可以观察到,如果我们去掉ng repeat,并且只有一个指令,它可以工作,但是如果我们有多个指令,则它不工作。

例如

有多个类似的指令

    <my-directive ng-model="foo" />
    <my-directive class="2" ng-model="foo" />

将只创建一个输入

使用ng重复的多个指令将完全破坏指令

<div ng-app="MyApp" ng-controller="MyCtrl">
    {{foo}}<br />
   <div ng-repeat="k in test">
       <my-directive ng-model="foo" />
   </div>
</div>

我不太明白为什么会发生这种事,有人能给我一些见解吗?

因此,您正试图将数组test中的每个值用作选项,当单击其中一个值时,foo(您的ngModel)的值应更新为该选项的值。这是正确的吗?

如果是,请查看以下内容:http://jsfiddle.net/sscovil/btshp2a3/

指令

myApp.directive('myDirective', function () {
  return {
    scope: {
      options: '='
    },
    require: 'ngModel',
    template: '<ul><li ng-repeat="option in options"><button ng-click="select(option)">{{ option }}</button></li></ul>',
    link: function(scope, iElement, iAttrs, ngModelController) {
      scope.select = function(option) {
        ngModelController.$setViewValue(option);
      };
    }
  };
});

用法

<my-directive ng-model="foo" options="test"></my-directive>

请注意,该指令需要元素上的ngModel。然后,它基于options变量创建一个可单击选项列表,该变量应该是一个数组。单击某个选项时,该指令会将更改通知ngModel控制器。

这是一篇很棒的文章,它解释了如何在自定义指令中使用NgModelController来做更有趣的事情。