AngularJS隔离范围与集合不起作用

时间:2015-01-23 21:11:49

标签: angularjs scope

我想使用同一指令的多个实例来呈现集合。我使用隔离范围将数组映射到隔离范围中的名称。隔离范围中的链接函数正确地看到映射的数组,但是其中的ng-repeat不起作用。

<html ng-app="MyApp">
  <head>
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript">
    var MyCtrl = function($scope) {
      $scope.blah = [1,2,4,5];
      $scope.bar = [14,52,64,25];
    }
    angular.module("MyApp", [])
    .directive("sephBlah", function($parse) {
        return {
          scope: {
            tags: "=sephBlah"
          },
          link: function(scope, elem, attrs) {
            console.log(scope.tags[0]);
          }
        }
    });
    </script>
  </head>
  <body ng-controller="MyCtrl">
      <div seph-blah="blah">
        <p data-ng-repeat="t in tags">{{t}}</p><!-- why this renders nothing? -->
      </div>

      <div seph-blah="bar">
        <p data-ng-repeat="t in tags">{{t}}</p><!-- why this renders nothing? -->
      </div>
  </body>
</html>

我不确定为什么ng-repeat什么都不呈现。链接功能正确地看到了数组。

1 个答案:

答案 0 :(得分:1)

你不应该使用这样的指令。您尝试使用控制器来完成此类功能。

使用指令时,请使用templatetemplateUrl属性提供内容。所以这将有效:

.directive("sephBlah", function($parse) {
    return {
      scope: {
        tags: "=sephBlah"
      },
      template: '<p data-ng-repeat="t in tags">{{t}}</p>',
      link: function(scope, elem, attrs) {
        console.log(scope.tags[0]);
      }
    }
});

在html中只做:

<div ng-attr-seph-blah="blah"></div>