如何在Angular JS指令模板中使用ng-repeat

3

我遇到了一个问题,无法在我的指令模板中展示控制器传递的JSON对象数据。以下是我的代码。

指令

app.directive('heroes', function(){
    return{
        scope:{
            heroes: '='
        },
        template: '<li ng-repeat="x in hereos">{{ x.Name }} </li>', // DOESNT WORK
        link:function(scope,element,attributes){

            });
        }
    }
});

控制器

app.controller('MainController',function($scope, $http){
    $scope.getData = function(){
          $http({
              url: 'js/directives/herolist.php',
              method: "GET"
        }).success(function (data) { $scope.heroes = data.records; })

    }

也许你应该在 $http 回调函数中尝试使用 $scope.$apply()。 - scokmen
$apply是做什么用的?你是指$http.$apply吗? - drake24
@scokmen $http会触发$digest。 - Shushanth Pallegar
猜测 ng-repeat="x in hereos"> 是一个打字错误吧?(Hereos 而不是 heroes) - Peter
1个回答

3

这里是可工作的Plunkr

你需要在HTML中包含指令并稍微重命名你的值

HTML可以是:

 <heroes data="heroes"></heroes>

那么在你的指令中,你需要这样做:
 scope:{
        heroes: '=data' 
    }

如果您要使用指令“heroes:=”,且不限制该指令的使用范围(比如只限制在某个元素中),则基本上会将该指令包含两次(这是不必要的)。如果您想将“heroes”作为属性使用,例如:

<heroes heroes="heroes"></heroes>

请在您的指令中添加

restrict: "E"

即可。


是的,仍然一样,无法显示。 - drake24
谢谢!这个有效了。只是一个问题,<heroes data="heroes"></heroes>我总是需要在指令的作用域内发布“= heroes”吗?顺便问一下,这是什么意思? - drake24
在这种情况下,是的。您正在从控制器传递数据到指令中。在您的控制器中,您有 $scope.heroes = data.records; 如果那是 $scope.myData 那么您将会做 <heroes data="myData"></heroes>。该指令具有其自己的作用域,在指令中,您可以定义属性以轻松地传递数据(参见:scope:{heroes:'=data'})。这就是您将指令的数据属性的值链接到指令作用域的位置。希望这让您更清楚一些。我建议您阅读更多关于指令的内容,以获得清晰的理解。 - rmuller
谢谢Muller!是的,我现在正在观看有关指令的视频。恰好我刚刚在你的答案中偶然发现了“=<somevariable>”。我以为它只限于“=”,“@”等符号。但无论如何,再次感谢! - drake24
谢谢您提供这个 Plunkr,救了我的命。 - Andre Aquiles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接