我试图测试一个角度指令。我之前没有遇到任何问题,但是今天我被卡住了。肯定是一个愚蠢的错误。
var element, scope, controller;
beforeEach(function() {
angular.mock.module('templates');
angular.mock.module('myApp.ui.apps.myMod');
angular.mock.module('myApp.ui.apps.myMod.dropdown-parameter');
angular.mock.inject(function($compile, $rootScope, $templateCache, $controller){
scope = $rootScope;
element = angular.element('<dropdown-parameter name-value-list="nameValueList" selected-option="selectedOption"></dropdown-parameter>');
scope.nameValueList = [];
var firstEnumValue = {
"Name":"TestMock",
"Value":"TestMock1Value"
};
var secondEnumValue = {
"Name":"TestMock",
"Value": "TestMock2Value"
};
scope.nameValueList.push(firstEnumValue);
scope.nameValueList.push(secondEnumValue);
scope.selectedOption={};
$compile(element)(scope);
scope.$digest();
controller = $controller('dropdownParameterController' ,{$scope: scope});
});
});
fit('Given an instantiated controller for dropdown parameter component when html is rendered then default value is the first one in the nameValueList', function(){
console.log(controller); // HERE RETURNS {}
expect(controller.selectedOption).toBe(controller.nameValueList[0].Value);
});
问题是控制器总是等于空对象
console.log(controller)=====&gt; {} 我做错了什么?
这是我的控制器&amp;&amp;指令代码。
var angular = require('angular');
module.exports = angular.module('myApp.ui.apps.myMod.dropdown-parameter', [])
.controller('dropdownParameterController', ['$scope', function($scope){
var self = this;
if(self.nameValueList)
{
self.selectedOption = self.nameValueList[0].Value;
}
}])
.directive('dropdownParameter', function(){
return {
restrict: 'E',
scope: true,
bindToController: {
nameValueList:'=',
selectedOption:'='
},
templateUrl: 'app/ui/apps/diagnostics/dropdown-parameter/dropdown-parameter.html',
controllerAs: 'dropdownParameterCtrl',
controller: 'dropdownParameterController'
};
});
答案 0 :(得分:0)
最后我解决了它。
Angular检测何时不使用注射。在我的情况下是&#34; $ scope&#34;。在我的控制器中使用后,一切都开始正常工作。
.controller('dropdownParameterController', ['$scope', function($scope){
var self = this;
self.scope = $scope;
if(self.nameValueList)
{
self.selectedOption = self.nameValueList[0].Value;
}
}])