图片常量
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}}"
而不是完整的绝对路径。
答案 0 :(得分:1)
将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
};
}]);
答案 1 :(得分:0)
您可以像任何其他角度提供者一样注入常量:
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
};
}]);
答案 2 :(得分:0)
将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/>
注意强>
将HTML上的streamingLogo
更改为streaming-logo
答案 3 :(得分:0)
你必须注入常量作为指令的依赖
myApp.directive("streamingLogo", function (imageConstant) {
var linker = function (scope, element, attrs) {
};
return {
restrict: "A",
link: linker
};
});
请注意,如果您希望将javascript文件用于生产,则需要以其他方式(check this)注入依赖项。
myApp.directive("streamingLogo", ['imageConstant',function (imageConstant) {
var linker = function (scope, element, attrs) {
};
return {
restrict: "A",
link: linker
};
}]);
答案 4 :(得分:0)
您需要将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/>