我正在尝试构建一个Angular属性指令,该指令接受'prefix'和'state',并根据这些值为元素添加一个类。我遇到的问题是该属性似乎只接受一个字符串。下面我将'前缀'传递给我的指令中的函数,并以非常迂回的方式获得状态。有没有办法将'prefix'和'state'传递给这个属性指令?
(function() {
'use strict';
angular.module('app')
.directive('playerState', playerStateDirective)
;
playerStateDirective.$inject = [];
function playerStateDirective() {
var postLink = function(scope, iElem, iAttrs) {
function setClass(prefix) {
var optionalTrailingDash = /(-)?$/;
prefix = String(prefix || '').replace(optionalTrailingDash, '-');
var state = scope.$parent.vm.player.player_state;
var map = {
active: prefix === 'bg-' ? 'info' : 'primary',
closed: 'danger'
};
var playerStateClass = prefix.concat(map[state] || 'default');
iElem.addClass(playerStateClass);
};
iAttrs.$observe('playerState', setClass);
};
return {
link: postLink,
restrict: 'A'
};
}
})();
指令使用:
<a player-state="text" ng-href="/players/{{vm.player.id}}">{{vm.player.email}}</a>