为什么我的自定义AngularJS指令在select选项中不起作用?

时间:2014-03-30 20:40:09

标签: javascript angularjs

我有一个我想在select选项元素中使用的自定义指令。我明确地不想将select移动到指令的模板中,因为我也在其他地方使用相同的指令。不幸的是,我不能让它在一个选择选项中工作,可能是因为有一些复杂的细节,我还不明白。想法,任何人?

这是我的简化示例,源自文档示例(也在http://plnkr.co/edit/Cod5menNABfeETTtah45?p=preview上的Plunker上):

    

<head>
  <meta charset="UTF-8">
  <title>Directive not working in select option</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>
  <script>
    angular.module('docsSimpleDirective', [])
      .controller('Controller', ['$scope',
        function($scope) {
          $scope.customerId = 2;
          $scope.customers = {
            '1': {
              name: 'Naomi',
              address: '1600 Amphitheatre'
            },
            '2': {
              name: 'Jim',
              address: '1200 South'
            }
          };
        }
      ])
      .directive('myCustomer', function() {
        return {
          scope: {
            cust: '='
          },
          template: '{{cust.name}}'
        };
      });
  </script>
</head>

<body ng-app="docsSimpleDirective">
  <div ng-controller="Controller">
   <h3>Simple ng-repeat (Works)</h3>
    <ul>
      <li ng-repeat="(cid, cust) in customers"><span>Plain: {{cust.name}}</span> / Directive: <span my-customer cust="cust"></span>
      </li>
    </ul>
    <h3>Select Options (Does not work)</h3>
    <select ng-model="customerId">
      <option ng-repeat="(cid, cust) in customers" value="{{cid}}" ng-selected="cid == customerId">
        Plain: <span>{{cust.name}}</span> / Directive: <span my-customer cust="cust"></span>
      </option>
    </select>
    <br/>{{customers[customerId].address}}
    <br/>(<span my-customer cust="customers[customerId]"></span>)
  </div>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

BenCr的评论是正确的。由于跨度,它不起作用。谢谢!如果我直接在option元素上使用该指令,它确实可以工作:

<body ng-app="docsSimpleDirective">
  <div ng-controller="Controller">
   <h3>Simple ng-repeat</h3>
    <ul>
      <li ng-repeat="(cid, cust) in customers" my-customer cust="cust"></li>
    </ul>
    <h3>Select Options</h3>
    <select ng-model="customerId">
      <option ng-repeat="(cid, cust) in customers" value="{{cid}}" ng-selected="cid == customerId" my-customer cust="cust"></option>
    </select>
    <br/>{{customers[customerId].address}}
    <br/>(<span my-customer cust="customers[customerId]"></span>)
  </div>
</body>

New Plunker:http://plnkr.co/edit/Cod5menNABfeETTtah45?p=preview