developer tip

AngularJS의 재사용 가능한 구성 요소

copycodes 2020. 12. 31. 22:16
반응형

AngularJS의 재사용 가능한 구성 요소


나는 AngularJS지금까지 그것을 처음 사용 하고 좋아합니다. 문서를 찾을 수없는 한 가지 문제는 다음과 같습니다.

반복 HTML이있는 페이지, 하위 카테고리가 모두 동일한 html 템플릿을 가진 카테고리 페이지가 있습니다. 내가 현재하고있는 것은 단일 컨트롤러가 모든 Json을 한 번에로드하는 것입니다. 나는 그것을 하위 뷰 ( ASP.NET MVC의 부분과 같은)로 나누고 싶지만 각 뷰는 초기화 할 때 서비스에 대한 자체 호출을 만듭니다. 또한 카테고리 이름을 매개 변수로 전달하고 싶습니다.

가장 효율적인 방법은 무엇입니까? 또한 Directives로 시도했지만 각 호출에 대해 범위를 별도로 유지하는 것은 운이 좋지 않습니다. 더 자세한 정보가 필요하면 알려주세요.


마침내이 문제를 해결할 수있었습니다. 문서를 읽고 놀면 꽤 쉽습니다.

다음은 지시문입니다.

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;
        });

    }
}
});

이것은 동일한 구성 요소가 여러 번 호출되지만 매개 변수가 다른 메인 페이지입니다.

    <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>

참조 URL : https://stackoverflow.com/questions/13619264/reusable-components-in-angularjs

반응형