@jaime您的回答很好。但是,如果您的页面具有$ http.get,则可以使用ng-if
app.directive('backImg', function(){
return function($scope, $element, $attrs){
var url = $attrs.backImg;
$element.css({
'background-image': 'url(' + url + ')',
'background-size': 'cover'
});
}
});
在工厂里
app.factory('dataFactory', function($http){
var factory = {};
factory.getAboutData = function(){
return $http.get("api/about-data.json");
};
return factory;
});
在控制器区域
app.controller('aboutCtrl', function($scope, $http, dataFactory){
$scope.aboutData = [];
dataFactory.getAboutData().then(function(response){
// get full home data
$scope.aboutData = response.data;
// banner data
$scope.banner = {
"image": $scope.aboutData.bannerImage,
"text": $scope.aboutData.bannerText
};
});
});
如果您使用ng-if(如下所示),则将通过插值获取图像,否则将无法获取图像,因为伪指令在HTTP请求之前获取了值。
<div class="stat-banner" ng-if="banner.image" background-image-directive="{{banner.image}}">