简体   繁体   English

使用JSON创建简单的指令

[英]Creating a simple directive with JSON

I am creating a simple pattern library with an index page of HTML patterns, and individual pages for each pattern. 我正在创建一个简单的模式库,其中包含HTML模式的索引页以及每个模式的单独页面。

I am thinking that I should create a "pattern" directive that would include the template for the index page patterns. 我在想应该创建一个“ pattern”指令,其中应包括索引页面模式的模板。 Like this: 像这样:

<pattern></pattern>

which would show: 这将显示:

<section ng-repeat="pattern in patterns | orderBy:'title'" class="pattern-type" data-anchor="{{pattern.anchor}}" id="{{pattern.id}}">
    <h3>{{pattern.title}} <a href="individuals/{{pattern.anchor}}">individuals/{{pattern.anchor}}</a></h3>
    <div class="pattern-desc" ng-show="pattern.description">
        <p>{{pattern.description}}</p>
    </div>
    <div class="pattern" ng-include="'individuals/' + {{pattern.anchor}}"></div>
    <div class="pattern-status">
        Date Posted: <span class="date"> {{pattern.updated | date:'yyyy-MM-dd'}}</span>
    </div>
</section>

I would create a separate "individual" directive for the individual pattern display template. 我将为各个模式显示模板创建一个单独的“个人”指令。 My app.js look like this: 我的app.js看起来像这样:

app.directive('pattern', function() {
    return {
        restrict: 'E', 
        templateUrl: 'pattern.html',
        controller: function() {
            $http.get('assets/js/components.json')
                .then(function(result) {
                    $scope.patterns = result.data;
                });
        },
        controllerAs: 'patterns'
    };
});

And my JSON looks like this: 我的JSON看起来像这样:

[{
    "id": "alerts", 
    "anchor": "alerts", 
    "title": "Alerts", 
    "description": "This is a desc", 
    "guidelines": "", 
    "updated": "2015-06-26"
},
{
    "id": "buttons", 
    "anchor": "buttons", 
    "title": "Buttons", 
    "description": "", 
    "guidelines": "", 
    "updated": "2015-04-15"
}]

However nothing is showing up. 但是什么都没有出现。 What am I missing? 我想念什么?

Your directive controller has missing $http & $scope dependency inside its function. 您的指令控制器在其函数内缺少$http$scope依赖性。

Code

    controller: function($scope, $http) { //<-- added dependency here
        $http.get('assets/js/components.json')
            .then(function(result) {
                $scope.patterns = result.data;
        });
    },

Working Plunkr 工作朋克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM