如何在Angular JS中的ng-include指令中包含参数函数

时间:2014-03-26 07:50:44

标签: javascript php angularjs controller

我试图在ng-include指令中包含函数。该函数接受参数并基于此加载动态内容。

我使用以下语法来实现此功能但不起作用。

<div ng-controller="MyCtrl">
<div ng-include src="'getCategoryDetail(cat_id)'"></div>
<div>{{results}}</div>
</div>

这是我的控制器

  myapp.controller('MyCtrl', function($scope, $http) {
        $scope.getCategoryDetail=function(catid)
        {
            $scope.catid=catid;
            $http.post('categoryDetail.php',{catId:scope.catid}).success(function(data) {
            $scope.results=data;
            })
        };
    });

2 个答案:

答案 0 :(得分:0)

我认为它不起作用,因为你在getCategoryDe​​tail函数中执行异步调用。此外,您将POST的结果分配给结果&#39;范围变量,但您不能在include中的任何位置使用它。

这篇文章可能会回答您的问题。 Angular.js directive dynamic templateURL

答案 1 :(得分:0)

我认为自定义指令可以提供很多帮助。

在您的主控制器中:

myapp.controller('MyCtrl', function($scope) {
    $scope.categoryIds = ids //I don't know where these come from, but that's up to you.
});

然后你可以定义一个指令,让我们称之为类别

myapp.directive('category', ['$http', function ($http) {
return {
    restrict : 'A',
    template : '<div>{{results.dataItem1}}</div>', //You could define your template in an external file if it is complex (use templateUrl instead to provide a URL to an HTML file)
    replace: true,
    scope: {
        category: '@',
    },
    controller: ['$scope', '$element', '$attrs', '$http',
        function($scope, $element, $attrs, $http) { 
            $http.post('categoryDetail.php', {catId:$scope.category}).success(function(data) {
                $scope.results = data;
            });
        }]
    };
}])

现在我们可以使用我们的指令了。在您的主HTML页面中:

<div ng-controller="MyCtrl">
    <div ng-repeat="catId in categoryIds" category="catId"></div>
</div>

这将为每个类别ID呈现一个div,每个都将加载自己的数据。希望这会有所帮助。我还没有对此进行测试,因此可能需要进行一些调整。