Didn"t forge 2018-08-07 21:45 采纳率: 25%
浏览 36

AngularJS Ajax内容加载器

I am trying to use angularJS to load contents of my HTML from ajax calls. I would like to have a single method with different parameters to vary ajax/REST uri and display results in different components. The (non-running version) code looks something like this:

app.controller('ContentController', function($scope, $sce, $http) {
  $scope.FetchContent = function(pageId) {
    let contentUri = 'https://somewhere/restendpoint/?id=' + pageId;

    $http.get(contentUri).then(function(data) {
      return $sce.trustAsHtml(data.data.d[0].Content);
    }
  }
})
<div ng-controller="ContentController" class="row">
  <div class="col-md-4" ng-bind-html="FetchContent('home')"></div>
  <div class="col-md-4" ng-bind-html="FetchContent('welcome')"></div>
  <div class="col-md-4" ng-bind-html="FetchContent('contact')"></div>
</div>

I end up getting tons of ajax calls generated from this. I've tried creating a custom directive, but it updates all elements with same data. Can anyone give me a pointer? Thanks!!

  • 写回答

1条回答 默认 最新

  • weixin_33693070 2018-08-07 22:02
    关注

    So.. I was able to get around the repeating ajax calls by using directives instead, and had to embed element Id to lock down the element:

    app.controller('ContentController', function($scope, $sce, $http) {
      $scope.FetchContent = function(pageName, elem) {
        var contentUri = 'https://somecontent/restendpoint/?id=' + pageName;
        $http.get(contentUri).then(function (data) {
          $('#' + elem).html(data.data.d[0].HTMLContent);
        });
      }
    });
    
    
    app.directive('loadcontent', function($parse) {
      return {
        restrict: 'A',
        link: function ($scope, elem, attrs) {
          elem.ready(function() {
            $scope.$apply(function() {
              var func = $parse(attrs.loadcontent);
              func($scope, elem)
            });
          });
        }
      };
    });
    
    <div ng-controller="ContentController" class="row">
      <div class="col-md-4" id="e1" loadcontent="FetchContent('home', 'e1')"></div>
      <div class="col-md-4" id="e2" loadcontent="FetchContent('home', 'e2')"></div>
      <div class="col-md-4" id="e3" loadcontent="FetchContent('home', 'e3')"></div>
    </div>
    

    It works and it inserts unique contents into own elements, but I really don't like the way and can't help but think there's gotta be a better and proper ways to do this... Any ideas from angularJS gurus?

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?