[英]AngularJS - Display image using directive
圖像常數
angular.module('app-config', []).constant('imageConstant',
{
logoPath: 'assets/img/logo/',
faviconPath: 'assets/img/favicon/',
layoutPath: 'assets/img/layout/',
logoFileName: 'myLogo.png'
});
指示
myApp.directive("streamingLogo", function () {
var linker = function (scope, element, attrs) {
//pass image constants here to append image url
//for ex: src = imageConstant.logoPath + imageConstant.logoFileName;
};
return {
restrict: "A",
link: linker
};
});
的HTML
<img class="my-logo" id="my-logo" ng-src="{{src}}" streamingLogo/>
想法是為圖像路徑和名稱提供一個配置文件,以便在HTML中僅傳遞ng-src="{{src}}"
而不是完整的絕對路徑。
將imageConstant
依賴項添加到您的指令中,就可以了,就像這樣:
myApp.directive("streamingLogo", ['imageConstant', function(imageConstant) {
var linker = function (scope, element, attrs) {
scope.logoPath = imageConstant.logoPath;
scope.favIconPath = imageConstant.faviconPath;
scope.layoutPath = imageConstant.layoutPath;
scope.logoFileName = imageConstant.logoFileName;
};
return {
restrict: "A",
link: linker
};
}]);
將imageConstant
注入到指令中,並將app-config
添加為模塊依賴項。
myApp.directive("streamingLogo", function (imageConstant) {
var linker = function (scope, element, attrs) {
scope.src= imageConstant.logoPath;
};
return {
restrict: "A",
link: linker
};
});
然后在linker
功能
然后用HTML
<img class="my-logo" id="my-logo" ng-src="{{src}}" streaming-logo/>
注意
更改streamingLogo
到streaming-logo
上的HTML
您可以像其他任何角度提供程序一樣注入常量:
myApp.directive("streamingLogo", ['imageConstant', function (imageConstant) {
var linker = function (scope, element, attrs) {
console.log(imageConstant.logoPath);
console.log(imageConstant.faviconPath);
console.log(imageConstant.layoutPath);
};
return {
restrict: "A",
link: linker
};
}]);
您必須將常量作為指令的依賴項注入
myApp.directive("streamingLogo", function (imageConstant) {
var linker = function (scope, element, attrs) {
};
return {
restrict: "A",
link: linker
};
});
請注意,如果要最小化用於生產的javascript文件,則需要以其他方式注入依賴項( 選中此選項 )。
myApp.directive("streamingLogo", ['imageConstant',function (imageConstant) {
var linker = function (scope, element, attrs) {
};
return {
restrict: "A",
link: linker
};
}]);
您需要將imageConstant
注入.directive
函數。
var myApp = angular.module('app-config', []);
myApp.directive("streamingLogo", ['imageConstant', function(imageConstant) {
return {
restrict: "A",
link: function (scope, elem, attrs) {
scope.logoPath = imageConstant.logoPath;
scope.favIconPath = imageConstant.faviconPath;
scope.layoutPath = imageConstant.layoutPath;
scope.logoFileName = imageConstant.logoFileName;
}
};
}]);
HTML代碼中的小變化:
使用streaming-logo
代替streamingLogo
。
<img class="my-logo" id="my-logo" src="{{logoPath}}" streaming-logo/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.