angularjs – 如何使用编译元素访问单元测试中的controllerAs命
发布时间:2020-12-17 17:38:14 所属栏目:安全 来源:网络整理
导读:在这个小提琴 http://jsfiddle.net/FlavorScape/fp1kktt9/我尝试在控制器上设置属性,而不是直接在$scope.在模板中(在生产中)我们只做myAliasCtrl.somePropertyList和ng-repeat工作. 但是,这在测试中不起作用.我不知道如何在控制器上获取/分配属性. 更新: 我
在这个小提琴
http://jsfiddle.net/FlavorScape/fp1kktt9/我尝试在控制器上设置属性,而不是直接在$scope.在模板中(在生产中)我们只做myAliasCtrl.somePropertyList和ng-repeat工作.
但是,这在测试中不起作用.我不知道如何在控制器上获取/分配属性. 更新: 但是,我的问题仍然是,我如何获得对该编译控制器的引用来说,创建一个间谍? (或者只是获得别名控制器的引用)? 这是来源: angular.module('myApp',[]) .directive('myTestDirective',function () { return { restrict: 'E',scope: { myBinding: '=' },replace: true,template: '<div ng-if="isRendered">TEST<div ng-repeat="foo in myCtrl.fooList">{{foo}}</div></div>',controller: 'myTestController',controllerAs: 'myCtrl' }; }) .controller('myTestController',function($scope) { $scope.isRendered = true; // if i reference this,ng-repeat works $scope.fooList = ["boob","cat","Tesla"]; }); describe('myTest directive:',function () { var scope,compile,validHTML; validHTML = '<div><my-test-directive my-binding="isRendered"></my-test-directive></div>'; //i beforeEach(module('myApp')); beforeEach(inject(function($compile,$rootScope){ scope = $rootScope.$new(); scope.isRendered = true; compile = $compile; })); function create() { var elem,compiledElem; elem = angular.element(validHTML); compiledElem = compile(elem)(scope); scope.$digest(); return compiledElem; } it('should have a scope on root element',function () { var el = create(); // how to get the controller??? el.scope().myCtrl.fooList = ["monkey","apple","Dishwasher"]; // notice it just has <!-- ng-repeat console.log( el ); expect(el.text()).toContain('TEST'); }); }); 解决方法
一切都按预期工作:)你只是试图访问错误的范围.
因为ngIf创建了一个新范围,所以应该访问该范围(因为在该子范围上创建了isRendered: expect(el.children().first().scope().isRendered).toBeTruthy(); 这是updated fiddle. 更新: 您正在使用controllerAs,基本上您将控制器绑定到范围属性.例如. controllerAs:’myTestCtrl’隐式导致$scope.myTestCtrl = this; (这是控制器实例. 但是你再次尝试访问错误的元素.你需要包装的第一个子元素< div>然后你需要它的隔离范围(不是正常范围): var ctrl = el.children().first().isolateScope().myTestCtrl; Another updated fiddle (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |