3

我正在玩 angularjs 并具有以下 HTML:-

   <div ng-app="App">
      <div ng-controller="AppCtrl">
         <products></products>
      </div>
   </div>

我的 js 看起来像这样:-

var app = angular.module('App', []);

app.controller("AppCtrl", function($scope, $http) {
   $http.get('/api/products')
      .then(function(res) {
         $scope.products = res.data;
   });
});

app.directive("products", function () {
   return {
      restrict: "E",
      template: "<h1>Products</h1><ul><li ng-repeat='product in products'>{{product.Name}} - <em>{{product.Category}}</em></li></ul>",
   };
});

这非常有效,但我不确定指令如何知道控制器在模板呈现结果之前已加载数据。所以我的问题是:-

是在这种情况下使用 a 的推荐方法$http.get(解释会很好),或者如果不是,那么推荐的方法是什么?

4

1 回答 1

2

I think this is a fine use of $http.get. At the end of the day, it's just a tool for doing ajax requests.

It seems your question stems from a fear that your directive will mysteriously break in different scenarios, which is understandable. The key, then, is to understand that data binding is Angular's secret weapon.

One way to think about it, Angular compiles everything and throws it into an event / digest loop. So, it is able to detect dependencies, watch for changes to variables, and call dependent methods (such as your products directive) when those variables change.

The Angular guide does a great job of providing conceptual diagrams for further understanding, and it's here: http://docs.angularjs.org/guide/concepts

于 2013-04-21T19:18:46.613 回答