在angular.js中,对于指令,我想根据template
与attr.checkType
一起使用的内容指定if then
键的属性。我怎么能这样做?我知道放置逻辑的唯一地方是链接功能,但模板键/属性不在链接功能之内。
angular.module('monitorApp')
.directive("countDown", [ 'sseHandler', function (sseHandler) {
function _bindMessage(scope, message) {
scope.countFrom = message;
}
return {
restrict: 'E',
scope: {
countFrom: "=",
checkType: "@"
},
//WOULD LIKE TO PLACE IF THEN TO SPECIFY WHAT TYPE OF TEMPLATE TO
//USE ACCORDING TO ATTR.CHECKTYPE.
template : if (attr.checkType == "foo") {
'<div class="btn btn-block btn-inverse" id="api-time">'+
'Next update in   <span class="info-test">{{countFrom}}</span>'+
'  seconds} else
{
<h1> HI </h1>
},
link: function(scope, element, attr){
scope.countFrom = sseHandler.broadcastStamp[attr.checkType] || "initializing";
scope.$on('ONE_SEC', function() {
resultType = attr.checkType;
seconds = sseHandler.broadcastStamp[attr.checkType];
if (seconds < -3) {
seconds = "Snap! Broadcast is late." +
" Something is broke";
}
else if (seconds <0) {
seconds = "running a little late";
}
_bindMessage(scope,seconds);
});
}
}
}]);
答案 0 :(得分:1)
您只需使用单个模板,并在模板中使用ng-if:
template : '<div>' +
'<div ng-if="checkType == 'foo'" class="btn btn-block btn-inverse" id="api-time">'+
'Next update in   <span class="info-test">{{countFrom}}</span>'+
'  seconds}' +
'</div>' +
'<h1 ng-if="checkType != 'foo'">HI</h1>' +
'</div>'
答案 1 :(得分:1)
在您的下方找到一个指令,根据&#34; temp&#34;在模板列表中进行选择。属性值
module.directive('templateSwitch', ['$compile', function ($compile) {
var getTemplate = function (Type) {
var typelist = {
template1: '<div>view1</div>',
template2: '<div>view2</div>'
};
return typelist[Type];
}
return {
restrict: 'E',
link: function (scope, element, attrs) {
var templatelinker = function (listType) {
var html = getTemplate(listType);
element.html(html).show();
$compile(element.contents())(scope);
};
templatelinker(attrs.temp);
}
};
}])
使用它如下
<template-switch temp="template2"></template-switch>