如何将AJAX转换为angular js,并为数组的每个元素重复代码块?

How can I convert AJAX into angular js and repeat the code block for each element of an array?

本文关键字:元素 代码 AJAX 转换 angular js 数组      更新时间:2023-09-26

我想创建一个系统,其中一段代码从外部文本文件被导入并使用angular js重复。代码需要通过一些文本文件运行,并创建一个新的部分,每个我一直试图重写我的ajax代码从以前的问题在angular js,我似乎找不到一种方法,使其工作。在.

中调用angularjs

我的旧AJAX代码:

$.ajax({
    url : '../src/text/section1.txt',
    dataType: 'text',
    success : function (data) {
        $('#section1').append(data);
    },
});

这是我目前拥有的:

app.controller('sectionController', ['$scope', function($scope, $http) {
  $scope.sections = [
    {id: 1, title: 'Page 1', data: ''},
    {id: 2, title: 'Page 2', data: ''},
    {id: 3, title: 'Page 3', data: ''},
    {id: 4, title: 'Page 4', data: ''},
    {id: 5, title: 'Page 5', data: ''},];
  angular.forEach($scope.sections, function(id) {
    $http({
      url : '../../src/text/section' + $scope.sections.id +'.txt',
      dataType: 'text',
    }).success(function (data) {
      $scope.sections[id].data = data;
    });
  });
}]);

我的HTML是:

<div class="body">
            <div class="bodyBackground"></div>
            <div class="contentContainer" ng-controller="sectionController">
                <div id="sectionContainer" ng-repeat="section in sections">
                    <div id="section{{ section.id }}">
                        <h3 class="sectionTitle">{{ section.title }}</h3>
                        <div>{{ section.data }}</div>
                    </div>
                </div>  
            </div>
        </div>

Thanks in Advance

考虑在$scope中添加一个'data'属性。部分对象

$scope.sections = [
{id: 1, title: 'page 1', data: ''}
]

然后在你的HTTP成功设置响应数据到适当的节对象数据属性

  }).success(function (data) {
      section.data = data;
    });

和在HTML中绑定到section对象的data属性

    app.controller('sectionController', ['$scope', '$http', function($scope, $http) {
    $scope.sections = [
        {id: 1, title: 'Page 1', data: ''},
        {id: 2, title: 'Page 2', data: ''},
        {id: 3, title: 'Page 3', data: ''},
        {id: 4, title: 'Page 4', data: ''},
        {id: 5, title: 'Page 5', data: ''}];
    angular.forEach($scope.sections, function(section) {
        $http({
            url : '../../src/text/section' + section.id +'.txt',
            dataType: 'text'
        }).success(function (data) {
            section.data = data;
        });
    });
}]);