在这个小提琴
http://jsfiddle.net/FlavorScape/fp1kktt9/我尝试在控制器上设置属性,而不是直接在$scope.在模板中(在生产中)我们只做myAliasCtrl.somePropertyList和ng-repeat工作.
但是,这在测试中不起作用.我不知道如何在控制器上获取/分配属性.
更新:
我必须在我的测试环境中遇到一些奇怪的本地化问题,因为我确实让ng-repeat工作.注意有两个子元素,即使该属性在别名控制器上. http://jsfiddle.net/FlavorScape/2adn983y/2/
但是,我的问题仍然是,我如何获得对该编译控制器的引用来说,创建一个间谍? (或者只是获得别名控制器的引用)?
这是来源:
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();
更新:
您正在使用controllerAs,基本上您将控制器绑定到范围属性.例如. controllerAs:’myTestCtrl’隐式导致$scope.myTestCtrl = this; (这是控制器实例.
但是你再次尝试访问错误的元素.你需要包装的第一个子元素< div>然后你需要它的隔离范围(不是正常范围):
var ctrl = el.children().first().isolateScope().myTestCtrl;