【发布时间】:2016-12-05 21:00:46
【问题描述】:
我一直在尝试重构一些代码,使用指令而不是 img 标签。 我想根据我在指令中输入的值动态更改 ng-if 状态和 src。
现在代码看起来像:
指令-
'use strict';
angular.module('myApp').directive('listImg', function() {
return {
retrict: 'E',
templateUrl: 'templates/list-img.html',
scope: {
show: '@',
},
link: function($scope) {
$scope.iconImg;
if ($scope.show == "opt1") {
$scope.iconImg = "images/img1.png";
} else if ($scope.show == "opt2") {
$scope.iconImg = "images/img2.png";
} else if ($scope.show == "opt3") {
$scope.iconImg = "images/img3.png";
} else if ($scope.show == "opt4") {
$scope.iconImg = "images/img4.png";
}
}
}
});
模板-
<img ng-if="show" ng-src="{{iconImg}}" class="list-image">
然后-
<list-img show="{{item.opt1 ? 'opt1' : ''}}"></list-img>
我无法让它正常工作,而且感觉不是最佳实践...... 如果有人可以就如何改进/重写它提供一些建议,那就太好了!
谢谢
【问题讨论】:
-
也许这个小提琴的方向是对的:jsfiddle.net/yqgvw58t?
标签: javascript angularjs image directive