[英]AngularJS display json by directive
我對AngularJS沒什么問題,我想讓指令顯示從其他網站導入的json,指令正常工作,但它不顯示角度綁定中的任何內容(當我通過艱苦使用而使用此代碼時,一切正常。)
HTML
<div ng-app="docsIsolateScopeDirective">
<div ng-controller="Controller">
<my-post info="post"></my-post>
</div>
</div>
角度
(function(angular) {
'use strict';
angular.module('docsIsolateScopeDirective', ['ngSanitize', 'ui.bootstrap'])
.controller('Controller', ['$scope','$http','$sce', function($scope, $http, $sce) {
$http.get(link+'json=get_recent_posts&callback=&count=1').then(function(response, date, contents){
$scope.contents = response.data.posts;
$sce.trustAsHtml(contents);
});
}])
.directive('myPost', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'single-post.html'
};
});
})(window.angular);
單郵政.HTML
<article>
<div class="news-container">
<span class="news-category"><a href="">{{content.categories[0].title}}</a></span>
<h1 class="news-title">{{content.title}}</h1>
<span class="news-date">{{content.date}}</span>
<div class="news-image">
<img src="{{content.thumbnail_images.full.url}}" />
</div>
<!-- .news-image -->
<div class="news-entry">
<p ng-bind-html="content.content">{{content.content}}</p>
</div>
</div>
有任何想法嗎? :)
您將回復另存為
$scope.contents = response.data.posts;
然后您將指令變量傳遞給post
。 也許您應該傳遞contents
?
而且在您的指令中,您有customerInfo
content
。
您需要在模板single-post.html
使用customerInfo
,還將contents
范圍對象傳遞給指令
此外,正確使用trustAsHtml()
方法。
$scope.contents = $sce.trustAsHtml(response.data.posts);
這是一個簡化的示例:
(function(angular) { 'use strict'; angular.module('docsIsolateScopeDirective', []) .controller('Controller', ['$scope', function($scope) { $scope.contents = { title: "test" }; } ]) .directive('myPost', function() { return { restrict: 'E', scope: { customerInfo: '=info' }, template: '<article>\\ <h1 class="news-title">{{customerInfo.title}}</h1>\\ </article>' }; }); })(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="docsIsolateScopeDirective"> <div ng-controller="Controller"> <my-post info="contents"></my-post> </div> </div>
使用jsonp調用外部域總是更好。 你可以嘗試這樣做嗎?
$ http.jsonp('some / trusted / url',{jsonpCallbackParam:'callback'})
將網址列入白名單也很合適。
將$ scope.contents傳遞給info。
$scope.contents = response.data.posts;
<div ng-app="docsIsolateScopeDirective">
<div ng-controller="Controller">
<my-post info="contents"></my-post>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.