无法访问我的模板指令中的任何路径

时间:2018-06-18 14:06:52

标签: angularjs

我有这个指令,我试图通过HTTP GET方法获取一些新闻,基于一些选项

import publicListTpl from './public-list.html';

(() => {
    angular
        .module('news.crud.directives', [])
        .directive('newsPortalPublishedList', () => ({
            restrict: 'E',
            replace: true,
            templateUrl: publicListTpl,
            scope: {
                type: '@'
            },
            controller: ($scope, $http, FlashMessages) => {
                $http.get('/api/portal/'+$scope.type)
                    .then(response => $scope.news = response.data)
                    .catch(() => FlashMessages.add(FlashMessages.ERROR, 'La récupération des '+$scope.type+' a échoué.'));
            }
        })); })();

当我添加scope选项scope: {type: '@'}时,我无法访问我的publicListTpl模板中的任何已定义路由,例如url('news_edit', {id: news.id})将返回{{1} }}

这是我的html模板:

null

Ps:我甚至不知道源问题,因此您可以编辑问题以使其更清晰。

1 个答案:

答案 0 :(得分:1)

我对你的指令进行了一些更改,我使用了链接函数而不是控制器,我用news替换ng-repeat中的item,因为用单个项命名是不是一个好的选择你正在循环的数组的名称。

import publicListTpl from './public-list.html';
    
    (() => {
        angular
            .module('news.crud.directives', [])
            .directive('newsPortalPublishedList', ($http, FlashMessages) => ({
                restrict: 'E',
                replace: true,
                templateUrl: publicListTpl,
                scope: {
                    type: '@'
                },
                link: (scope) => {
                    $http.get('/api/portal/'+scope.type)
                        .then(response => scope.news = response.data)
                        .catch(() => FlashMessages.add(FlashMessages.ERROR, 'La récupération des '+scope.type+' a échoué.'));
                }
            })); })();
<div class="portlet" ng-repeat="item in news._embedded.items">
        <div class="portlet light bordered">
            <div class="portlet-title">
                <div class="caption">
                    {{ item.title }}
                    <small>{{ item.subtitle }}</small>
                </div>
                <div class="actions">
                    <a class="btn btn-info btn-sm" href="{{ url('news_edit', {id: item.id}) }}">
                        <i class="fa fa-pencil"></i> Editer
                    </a>
                </div>
            </div>
            <div class="portlet-body">
                <img ng-if="news.image" src="{{ item.image }}" class="pull-left" height="100"/>
                <div ng-bind-html="news.shortContent"></div>
            </div>
        </div>
    </div>

指令的使用应该是:

<news-portal-published-list type="url_goes_here"></news-portal-published-list>
相关问题