AngularJS - ng-switch v2
HTML
<div ng-controller="MyController">
Value read from global variable: {{myConstant}}
<p ng-repeat="item in items">
<span wlj-switch wlj-switch-on="item.value">
<span wlj-switch-when="myConstant">
<span class="blue">{{item.name}}</span>
</span>
<span wlj-switch-when="4">
<span class="red">{{item.name}}</span>
</span>
<span wlj-switch-default>
{{item.name}}
</span>
</span>
</p>
</div>
CSS
.red { color: red; }
.blue { color: blue; }
JavaScript
var app = angular.module('myApp', []);
app.run(function ($rootScope) {
$rootScope.myConstant = 2;
});
function MyController($scope) {
$scope.items = [
{ name: "one", value: 1 },
{ name: "two", value: 2 },
{ name: "three", value: 3 },
{ name: "four", value: 4 },
{ name: "five", value: 5 }
];
}
app.directive('wljSwitch', function () {
return {
controller: function ($scope) {
var _value;
this.getValue = function () {
return _value;
};
this.setValue = function (value) {
_value = value;
};
var _whensCount = 0;
this.addWhen = function (value) {
_whensCount++;
}
this.removeWhen = function (value) {
_whensCount--;
}
this.hasWhens = function () {
return _whensCount < -1;
};
},
link: function (scope, element, attrs, controller) {
scope.$watch(function () {
return scope.$eval(attrs.wljSwitchOn);
}, function (value) {
controller.setValue(value);
});
}
};
});
app.directive('wljSwitchWhen', function () {
return {
require: '^wljSwitch',
template: '<span ng-transclude></span>',
transclude: true,
replace: true,
link: function (scope, element, attrs, controller) {
scope.$watch(function () {
return controller.getValue() === scope.$eval(attrs.wljSwitchWhen);
}, function (value) {
if (value) {
controller.addWhen();
} else {
...