Reusable components in AngularJS

I am new to AngularJS and still love it. One of the problems that I cannot find is the following:

I have a repeating HTML page, a category page with subcategories, all of which have the same html template. What I'm doing now is that one controller loads all Json at the same time, which is slow. I would like to break it down into sub-views ( something like partial in ASP.NET MVC) , but each view will make it its own service call when it is initialized. I would also like to pass the category name as a parameter.

What is the most efficient way to do this? I also tried with the directives, but I was not lucky that the delimitation of the area was different for each call. Let me know if you need more information.

+54
angularjs
Nov 29 '12 at 5:12
source share
1 answer

Finally, I was able to solve this problem. This is pretty easy after you read the documentation and play with it.

Here is the directive:

 angular.module('components', []).directive('category', function () { return { restrict: 'E', scope: {}, templateUrl: '/Scripts/app/partials/CategoryComponent.html', controller: function ($scope, $http, $attrs) { $http({ url: "api/FeaturedProducts/" + $attrs.catName, method: "get" }).success(function (data, status, headers, config) { $scope.Cat = data; }).error(function (data, status, headers, config) { $scope.data = data; $scope.status = status; }); } } }); 

This is the main page with the same component, which is called several times, but with a different parameter

  <ul class="unstyled"> <li> <category cat-name="Ultrabooks"></category> </li> <li> <category cat-name="Tablets"></category> </li> <li> <category cat-name="Laptops"></category> </li> <li> <category cat-name="Digital SLR Cameras"></category> </li> 

CategoryComponent.html

 <a href="#/Categories/{{Cat.CategoryName}}"> <h4>{{Cat.CategoryName}}</h4> </a> <div ng-switch on="status"> <div ng-switch-when="500" class="alert alert-error"> {{status}} {{data}} </div> <div ng-switch-default> <ul class="unstyled columns"> <li class="pin" ng-repeat="p in Cat.Products"> <a href="#/reviews/{{p.UPC}}"> <h5>{{p.ProductName}}</h5> <img src="{{p.ImageUrl}}"> </a> </li> </ul> </div> </div> 
+65
Dec 01 '12 at 18:44
source share



All Articles