javascript - 使用 Angular.js 的 ng-repeat 创建动态链接

标签 javascript angularjs dynamic angularjs-ng-repeat dynamic-linking

我正在使用 fake JSONplaceholder API 创建一个应用程序。我正在显示帖子列表,我希望 ng-repeated 帖子标题链接到帖 subview 。

这是 HTML:

    <body layout="column" ng-app="myApp" ng-cloak ng-controller="controller">
    <h1>{{apptitle}}</h1>
    <script type="text/ng-template" id="allposts.htm">
        <a href="#addpost">
    <button type="button" class="btn btn-primary addbtn" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
        Add a post
    </button>
</a>
        View
        <select ng-model="viewby" ng-change="setItemsPerPage(viewby)">
            <option>9</option>
            <option>18</option>
            <option>36</option>
            <option>100</option>
        </select>posts
        <div class="row" ng-repeat="collatedPostList in collatedPosts">
            <div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList">
                 <div class="inner">
                <a href="#/posts/{{post.indexOf(post)}}">{{post.title}}</a>
                <p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p>
            </div>
            </div>
        </div>
        <div class="text-center">
        <ul uib-pagination total-items="totalItems" ng-model="currentPage" class="pagination-sm"
            items-per-page="itemsPerPage" ng-change="pageChanged(currentPage)"></ul>
        </div>
    </script>
    <script type="text/ng-template" id="posts.htm">
  </script>
    <script type="text/ng-template" id="addpost.htm">
    <form ng-submit="addPost()" class="adding">
        <input id="titleadd" type="text" name="title" ng-model="newPost.title" placeholder="Add title">
        <br>
        <input id="textadd" type="text" name="body" ng-model="newPost.body" placeholder="Add some text">
        <br>
        <button type="submit" ng-click="addAlert(msg,'success')" class="btn btn-primary" id="submit" value="Submit">
        Post it
        </button>
        <a href="#allposts">
        <button type="button" class="btn btn-primary" >
            Go back to post list
        </button></a>
            <br>
        <uib-alert 
              ng-repeat="alert in alerts" 
              type="{{alert.type}}" 
              dismiss-on-timeout="5000" 
              close="alerts.splice($index, 1);">{{alert.msg}}
    </uib-alert>    </form>
  </script>
    <div ng-view></div>
    <script src="app.js"></script>
</body>

和JS:

Array.prototype.collate = function(collateSize) {
    var collatedList = [];

    if (collateSize <= 0) {
        return [];
    }
    angular.forEach(this, function(item, index) {
        if (index % collateSize === 0) {
            collatedList[Math.floor(index / collateSize)] = [item];
        } else {
            collatedList[Math.floor(index / collateSize)].push(item);
        }
    });

    return collatedList;
};

var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);

myApp.config(function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'allposts.htm',
        controller: 'PostsController'
    }).when('/posts', {
        templateUrl: 'posts.htm',
        controller: 'PostController'
    }).when('/addpost', {
        templateUrl: 'addpost.htm',
        controller: 'AddController'
    }).otherwise({
        redirectTo: '/'
    });
});

myApp.controller('PostsController', function($scope) {});

myApp.controller('PostController', function($scope) {});

myApp.controller('AddController', function($scope) {});


myApp.controller('controller', function($scope, $http) {
    $scope.apptitle = "My app";

    $http({
        method: 'GET',
        url: "http://jsonplaceholder.typicode.com/posts"
    }).then(function(response) {
        $scope.posts = response.data;
        $scope.viewby = 9;
        $scope.totalItems = $scope.posts.length;
        $scope.currentPage = 1;
        $scope.itemsPerPage = $scope.viewby;
        $scope.maxSize = 5;
        $scope.collatedPosts = getCollatedPosts($scope.posts);
        $scope.newPost = {};


    function getCollatedPosts(posts) {
        if (!posts) {
            return [];
        }

        var paginatedPosts = posts.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));
        return paginatedPosts.collate(3);
    }

    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
    };

    $scope.setItemsPerPage = function(num) {
        $scope.itemsPerPage = num;
        $scope.currentPage = 1; //reset to first page
        $scope.collatedPosts = getCollatedPosts($scope.posts);
    };

    $scope.pageChanged = function(currentPage) {
        $scope.currentPage = currentPage;
        $scope.collatedPosts = getCollatedPosts($scope.posts);
    };
        $scope.addPost = function(){
          $http.post("http://jsonplaceholder.typicode.com/posts",{
            title: $scope.newPost.title,
            body: $scope.newPost.body,
            usrId: 1
          })
          .success(function(data, status, headers, config){
            console.log(data);
            $scope.posts.push($scope.newPost);
            $scope.newPost = {};
          })
          .error(function(error, status, headers, config){
            console.log(error);
          });
    };});


    $scope.alerts = [];

    $scope.msg = "Well done! Your post was added";

    $scope.addAlert = function(msg, type) {
      $scope.alerts.push({
        msg: msg,
        type: type
      });
    };

});

我的代码无法运行。有 100 个重复帖子,我希望每个帖子标题都链接到帖 subview 。当前代码将每个标题链接到 #/posts 。我也尝试过<a href="#/posts/{{post.id}}">{{post.title}}</a> ,但没有成功。 这样做的正确方法是什么?

您可以看到完整代码here :

最佳答案

您可以通过以下方式调试代码。

console.log(response.data) // will give you data in success http get

然后

您可以通过 {{posts}} 以 HTML 格式打印这些数据,如果您在那里获得数据,那么您就走在正确的轨道上。

请尝试我的以下代码片段来链接帖子

var myApp = angular.module('myApp', []);
myApp.controller('PostController', ['$scope','$http', function($scope, $http) {
  var root = 'http://jsonplaceholder.typicode.com';
  
  $http({
    method: 'GET',
    url: root+'/posts'
  }).then(function successCallback(response) {
     $scope.posts= response.data;
  }, function errorCallback(response) {
    
  });
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PostController">
  <div ng-repeat="post in posts track by $index">
    <a ng-href="http://jsonplaceholder.typicode.com/posts/{{post.id}}">{{post.title}}</a> <br/>
  </div>
</div>

关于javascript - 使用 Angular.js 的 ng-repeat 创建动态链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39383390/

相关文章:

javascript - 将 MYSQL 的 PHP 输出格式化为 morris.js 图表数据

javascript - 使用 Web 服务在 Qualtrics 中拉取、操作响应并将其作为新问题发回

javascript - 图像源未与指令内的范围变量绑定(bind)

javascript - 使用 AngularJS 进行简单的 AJAX 调用

扩展实例的Java架构问题(需要模式推荐)

dynamic - invokedynamic 什么时候真正有用(除了惰性常量)?

javascript - 调整 div 高度,使其始终适合页面

javascript - 验证 JS 中开放时间之间的日期

javascript - 将对象添加到 Firebase 时设置自己的 key - AngularFire

c# - 为什么反射找不到属性