AngularJS ng-repeat在Django驱动的网页上不起作用

AngularJS ng-repeat doesn't work on Django powered webpage

本文关键字:网页 不起作用 ng-repeat Django AngularJS      更新时间:2023-09-26

我在我的 Django 驱动的网页中有 AngularJS 代码的 2 部分。

第一部分

<div class="categoryList">
        <ul>
            <li data-ng-repeat="cat in categories"> 
                <a>{$ cat.name $}</a>
            </li>
        </ul>
</div>

第 2 部分

<li data-ng-repeat="i in range(pictures[currentCat].length)">
    <a data-ng-click="changePage(i)">{$ i $}</a>            
</li>

这是我的控制器

$scope.currentPage = 1;
$scope.currentCat = 0;
$.getJSON('categories/', 
 function(data) {
    $scope.categories= data;
});
$scope.pictures=[cat1,cat2,cat3,cat4,cat5]; //cat1..cat5 are some dictionaries like 'categories'
$scope.changePage = function(i){
        $scope.currentPage=i;
    };
问题是第 2 部分在

加载页面时工作正常,但是第 1 部分不起作用,直到我单击第 2 部分列表中的页码并运行"changePage"

当我的网页不是由 Django 提供支持时,这工作正常

更新

views.py

def getcategories(request): // /categories/ url runs this 
    dictionaries = [obj.as_json() for obj in Category.objects.all()]
    return HttpResponse(json.dumps(dictionaries), content_type='application/json')

models.py

class Category(models.Model):
    name = models.CharField(default='other',max_length=50)
    upload_date = models.DateTimeField(default=datetime.now, blank=True)
    def as_json(self):
        return {
            "id": self.id,
            "name": self.name
        }

正如 simpe 所说,输出应该是{{cat.name}}{{i}}的。

关于"类别",检查 url 是否正常工作,然后使用浏览器开发人员工具查看是否调用了正确的 URL。

你也可以使用 django rest 框架和$resource在前端和后端之间发送数据。

$scope.$apply()添加到$.getJSON,现在它会在获得结果后立即更新$scope.categories。 现在一切正常。

$.getJSON('categories/', 
 function(data) {
    $scope.categories= data;
    $scope.$apply();
});