Tim*_*ter 6 javascript angularjs ng-switch rootscope
我正在使用AngularJS $rootScope对象来公开一些需要控制器和视图都可访问的全局常量:
var app = angular.module('myApp', []);
app.run(function ($rootScope) {
$rootScope.myConstant = 2;
});
Run Code Online (Sandbox Code Playgroud)
当我尝试在视图中呈现全局值时,它可以正常工作:
{{myConstant}}
Run Code Online (Sandbox Code Playgroud)
同样,如果我在ng-if条件中引用全局值,它也可以工作:
<span ng-if="someValue == myConstant">Conditional content</span>.
Run Code Online (Sandbox Code Playgroud)
但是,当尝试在ng-switch块中使用相同的值进行比较时,它永远不会计算为true.这个JSFiddle演示了我尝试让它工作的尝试.我也尝试显式引用常量值作为$rootScope表达式的成员和表达式(在双花括号内)但没有任何作用.
我有什么想法我做错了吗?
谢谢,
蒂姆
ng-switch-when您可以自定义ng-switch-on表达式,而不是尝试设置,以便在myConstant等于时生成特定值item.value:
<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>
Run Code Online (Sandbox Code Playgroud)
工作实例.
你总是可以自己推出......:)
(不确定这有多有效,而且还没有经过充分测试,因为我刚刚写了它)
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;');
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3647 次 |
| 最近记录: |