Reusable components in AngularJS

前端 未结 1 1057
鱼传尺愫
鱼传尺愫 2021-01-30 00:10

I am new to AngularJS and liking it so far. One problem I cannot find any documentation is this:

I have a page with recurring HTML, a category page with sub

相关标签:
1条回答
  • 2021-01-30 00:49

    I was finally able to solve this. It is pretty easy after your read the documentation and play around

    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 this the main page with the same component called multiple times but with 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>
    
    0 讨论(0)
提交回复
热议问题