如何根据条件附加指令

问题描述 投票:0回答:1

我有2个不同的指令。第一个是返回带有实时视频的iframe,第二个返回带有最近视频的iframe。

条件是:如果存在实时内容,则追加实时指令,否则追加最近的视频指令。

香港专业教育学院尝试使用普通的html而不是指令,它可以工作,但是当我放置指令元素时,遗憾的是它不起作用。

工作

controller.js

function isLiveOn() {

    var liveIframe = '<h2>LIVE</h2>';
    var videoIframe = '<h2>VIDEO</h2>';

    if (vm.live.items[0] != undefined) {
        $('.iframe-container').append(liveIframe);
    } else {
        $('.iframe-container').append(videoIframe);
    }

};

不工作

controller.js

function isLiveOn() {

    var liveIframe = '<live-iframe live="vm.live.items[0]"></live-iframe>';
    var videoIframe = '<last-video video="vm.activity.items[0]"></last-video>';

    if (vm.live.items[0] != undefined) {
        $('.iframe-container').append(liveIframe);
    } else {
        $('.iframe-container').append(videoIframe);
    }

};

每个指令都有自己的html和js文件。像这样的东西:

directive.html

<div class="live">
    <iframe ng-src="{{getIframeSrc(live.id.videoId)}}"></iframe>
</div>
<div class="live-description">
    <h4>{{live.snippet.title}}</h4>
</div>

directive.js

app.directive('live', live);

live.$inject = ['$window'];

function live($window) {

    var directive = {
        link: link,
        restrict: 'EA',
        templateUrl: 'path',
        scope: {
            live: '='
        }
    };

    return directive;

    function link(scope, element, attrs) {
        scope.getIframeSrc = function(id) {
            return 'https://www.youtube.com/embed/' + id;
        };
    }
} 

所以我认为它可能缺少指令的一些问题。任何帮助将不胜感激!

javascript angularjs angularjs-directive append conditional
1个回答
1
投票

您可以在UI中控制它,而不是处理控制器中的逻辑,因为它会更容易。

-----Other Html Codes-----
<live-iframe ng-if="vm.live.items[0]" live="vm.live.items[0]"></live-iframe>
<last-video ng-if="!vm.live.items[0]" video="vm.activity.items[0]"></last-video>
-----Other Html Codes-----

您可以从控制器中删除以下代码行

var liveIframe = '<live-iframe live="vm.live.items[0]"></live-iframe>';
var videoIframe = '<last-video video="vm.activity.items[0]"></last-video>';

if (vm.live.items[0] != undefined) {
    $('.iframe-container').append(liveIframe);
} else {
    $('.iframe-container').append(videoIframe);
}
© www.soinside.com 2019 - 2024. All rights reserved.