【问题标题】:Angular (1) directive, dynamically change ng-if state and img srcAngular(1)指令,动态改变ng-if状态和img src
【发布时间】: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>

我无法让它正常工作,而且感觉不是最佳实践...... 如果有人可以就如何改进/重写它提供一些建议,那就太好了!

谢谢

【问题讨论】:

标签: javascript angularjs image directive


【解决方案1】:

通过条件的身份检查以正确的方式使用ng-if,如

&lt;img ng-if="item.opt1!=''" src="{{item.opt1}}" /&gt;&lt;img ng-if="item.opt1==''" src="noimg.jpg" /&gt;

试试吧!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多