如何在ng-repeat中使每个指令共享相同的ng模型?

时间:2015-12-08 00:17:26

标签: javascript angularjs

这是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并且只有一个指令它可以工作,但是如果我们有多个指令它不起作用。

例如

拥有多个指令,例如this

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

只会创建一个输入

使用ng-repeat有多个指令将完全破坏指令

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

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

1 个答案:

答案 0 :(得分:0)

因此,您尝试使用数组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控制器更改。

Here is a great article解释了如何在自定义指令中使用NgModelController来处理更有趣的事情。