How to append directives based on conditions

2019-03-03 19:31发布

I have 2 different directives. The first one is returns an iframe with a live video, and the second returns an iframe with a recent video.

The condition is: if live content is present, append live directive, else append recent video directive.

Ive tried with normal html instead of the directives and it works, but when i put the directive element, unfortunately doesnt work.

WORKING

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);
    }

};

NOT WORKING

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);
    }

};

Each directive has its own html and js file. Something like that:

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;
        };
    }
} 

So im thinking its some problem with the directives that im probably missing. Any help will be appreciated!

1条回答
干净又极端
2楼-- · 2019-03-03 20:20

Instead of handling the logic in the controller you can control it in UI as it will be easier.

-----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-----

And you can remove following lines of code from the controller

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);
}
查看更多
登录 后发表回答