我有一个指令,我试图通过HTTP方法获取一些消息,基于一些选项
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})将返回null。
这是我的html模板:
<div class="portlet" ng-repeat="news in newsList">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
{{ news.title }}
<small>{{ news.subtitle }}</small>
</div>
<div class="actions">
<a class="btn btn-info btn-sm" href="{{ url('news_edit', {id: news.id}) }}">
<i class="fa fa-pencil"></i> Editer
</a>
</div>
</div>
<div class="portlet-body">
<img ng-if="news.image" src="{{ news.image }}" class="pull-left" height="100"/>
<div ng-bind-html="news.shortContent"></div>
</div>
</div>
</div>Ps:我甚至不知道源问题,所以你可以编辑这个问题,使它更清楚。
发布于 2018-06-18 14:28:55
我对您的指令做了一些更改,我使用了链接函数而不是控制器,我用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>https://stackoverflow.com/questions/50911329
复制相似问题