我正在尝试实现一个依赖于作用域变量的测试。我想让ng-switch-when解析表达式。这是我正在尝试做的事情(更新使用$rootScope):
it('should switch on array changes', inject(function($rootScope, $compile) {
element = $compile(
'<div ng-switch="select">' +
'<div ng-switch-when="test[0]">test[0]:{{test[0]}}</div>' +
'</div>')($rootScope);
expect(element.html()).toEqual('<!-- ngSwitchWhen: test[0] -->');
$rootScope.test = ["leog"];
$rootScope.select = "leog";
$rootScope.$apply();
expect(element.text()).toEqual('test[0]:leog');
}));
我的问题是,我为了让这个工作实现,写的代码中无法获取作用域变量“test”的值,它不像我期望的那样工作。这里是代码实现:
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 800,
require: '^ngSwitch',
compile: function(element, attrs) {
return function(scope, element, attr, ctrl, $transclude) {
var expr = scope.$eval(attrs.ngSwitchWhen),
ngSwitchWhen = expr !== undefined ? expr : attrs.ngSwitchWhen;
ctrl.cases['!' + ngSwitchWhen] = (ctrl.cases['!' + ngSwitchWhen] || []);
ctrl.cases['!' + ngSwitchWhen].push({ transclude: $transclude, element: element });
};
}
});
有人知道我错在哪里了吗?任何帮助都将不胜感激。
提前感谢!
更新
为了澄清,这是Angular团队测试ng-switch的示例。只是想展示我以类似的方式进行测试,但没有得到预期的结果。
而且,我忘记将我的代码反向到$rootScope,直到现在你看到的都是我试图创建一个新的作用域来避免依赖于$rootScope进行更改的尝试之一。
it('should switch on value change', inject(function($rootScope, $compile) {
element = $compile(
'<div ng-switch="select">' +
'<div ng-switch-when="1">first:{{name}}</div>' +
'<div ng-switch-when="2">second:{{name}}</div>' +
'<div ng-switch-when="true">true:{{name}}</div>' +
'</div>')($rootScope);
expect(element.html()).toEqual(
'<!-- ngSwitchWhen: 1 --><!-- ngSwitchWhen: 2 --><!-- ngSwitchWhen: true -->');
$rootScope.select = 1;
$rootScope.$apply();
expect(element.text()).toEqual('first:');
$rootScope.name="shyam";
$rootScope.$apply();
expect(element.text()).toEqual('first:shyam');
$rootScope.select = 2;
$rootScope.$apply();
expect(element.text()).toEqual('second:shyam');
$rootScope.name = 'misko';
$rootScope.$apply();
expect(element.text()).toEqual('second:misko');
$rootScope.select = true;
$rootScope.$apply();
expect(element.text()).toEqual('true:misko');
}));
$scope.test=...
移动到element = $compile...
上面一行,它还能正常工作吗? - Jonathan