javascript - AngularJS路由: get template with data

标签 javascript angularjs angular-routing

我有以下路由配置

myApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'partials/list.html',
        controller: 'contactListCtrl'
      }).
      when('/new', {
        templateUrl: 'app/partials/form.html',
        controller: 'contactAddCtrl'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

我的主页('/')只是加载了一些联系人,它的 contactListCtrl 就像

myApp.controller('contactListCtrl', function($scope, $http) {
    $http.get("list")
            .then(function(response) {
              $scope.contact_list = response.data;  
            });
});

因此,当我在浏览器上加载主页时,它会加载模板,然后向服务器发送另一个请求(“/list”)以获取联系人(json)。因此浏览器向服务器发送2个请求

在 AngularJS 开发中,同时发送 2 个请求来获取模板和数据是否正常?是否有任何解决方法可以仅发送 1 个请求来获取模板和数据?

如果我需要在这种情况下发送 2 个请求,并且假设我必须在主页中加载 5 个模板,那么我必须发送另外 5 个请求来将数据(来自数据库)绑定(bind)到每个模板?

最佳答案

您可以在路由中使用解析,这将加载数据并加载模板。您可以在这里查看解决方案http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

关于javascript - AngularJS路由: get template with data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991100/

相关文章:

javascript - 如何将 div id、class 作为参数传递给 anchor 标记 onclick 调用的函数?

javascript - 如何避免因观看结果而打开新窗口?

javascript - 在 ASP.NET MVC 应用程序中使用 AngularJS 发布表单

javascript - 当我更改语言时, Angular 翻译不会刷新 Controller 中的翻译

javascript - Angular - 从 JavaScript 重定向到路由

html - 当我在浏览器中粘贴 url 时, Angular 路由不存在

javascript - 每 30 秒更改一次 iframe 源。

javascript - 如何将 ng-content 与 ng-container 一起使用?

javascript - AngularJS 中的嵌套 View 不起作用

javascript - Angular 路由 html5mode ASP.NET