我正在使用AngularJS $rootScope
对象来公开一些全局常量,这些常量需要对控制器和视图都可访问:
var app = angular.module('myApp', []);
app.run(function ($rootScope) {
$rootScope.myConstant = 2;
});
当我试图在视图中呈现全局值时,它工作正常:
{{myConstant}}
同样,如果我引用ng-if
条件中的全局值,它也起作用:
<span ng-if="someValue == myConstant">Conditional content</span>.
但是,当尝试在ng-switch
块内使用相同的值进行比较时,它的计算结果永远不会为true。这个JSFiddle展示了我的尝试。我还尝试过将常量值显式引用为$rootScope
的成员和表达式(在双大括号内),但都不起作用。
你知道我做错了什么吗?
谢谢,
Tim
您可以自定义ng-switch-on
表达式,以在myConstant
等于item.value
:时生成特定值,而不是尝试设置ng-switch-when
<span ng-switch on="{true:'const', false: item.value}[myConstant == item.value]">
<span ng-switch-when="const">
<span class="blue">{{item.name}}</span> (emphasis applied by ng-switch)
</span>
<span ng-switch-when="4">
<span class="red">{{item.name}}</span> (emphasis applied by ng-switch)
</span>
<span ng-switch-default>
{{item.name}}
</span>
</span>
工作示例。
您可以随时滚动自己的…:)
(不确定这有多有效,也没有像我刚才写的那样经过很好的测试)
http://jsfiddle.net/H45zJ/1/
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 {
controller.removeWhen();
}
element.attr('style', value ? '' : 'display:none;');
});
}
};
});
app.directive('wljSwitchDefault', function () {
return {
require: '^wljSwitch',
template: '<span ng-transclude></span>',
transclude: true,
replace: true,
link: function (scope, element, attrs, controller) {
scope.$watch(controller.hasWhens, function (value) {
element.attr('style', value ? '' : 'display:none;');
});
}
};
});