以下指令检查/加载模板的值为“pass,fail,required”。 条件是
if(parent value == required){
1. if the value is true --> $scope.msg = "fail" --> loads the template with {{msg}} value
2. if the value is false --> $scope.msg = "pass" --> loads the template with {{msg}} value
}
详细说明,
加载模板:[showerror.html]
<div>{{msg}}</div>
指令致电:
<div show-error="obj"></div>
(obj包含obj.error和obj.required)
指令:
angular.module("dsf").directive('showError', [
function () {
'use strict';
return {
scope: {
obj: '=showError'
},
link: function ($scope) {
$scope.showError = {};
$scope.msg = "";
function setTemplate(filename) {
$scope.showError.template = 'app/path/' + filename + '.html';
}
$scope.$watch(function () {
if ($scope.obj.required === true) {
if ($scope.obj.error === false) {
$scope.msg = "Pass";
} else if ($scope.obj.error === "required") {
$scope.msg = "Required";
} else if ($scope.obj.error === true) {
$scope.msg = "fail";
}
} else {
if ($scope.obj.error === true) {
$scope.msg = "fail";
} else if ($scope.obj.error === false) {
$scope.msg = "Pass";
}
}
setTemplate("showerror");
});
},
template: '<div ng-include="showError.template"></div>'
};
}
]);
由于我是茉莉花测试的新手,我怎样才能为这个指令编写测试?有什么建议吗?
确定。我已经为这个指令编写了单元测试。现在有什么不对?
describe('showError', function () {
'use strict';
var compile, $scope, element;
beforeEach(module('dsf'));
beforeEach(inject(function ($compile, $rootScope) {
element = angular.element('<div show-error="obj"></div>');
$scope = $rootScope.$new();
compile = function (obj) {
$scope.obj = obj;
$compile(element)($scope);
$scope.$digest();
};
}));
it('updates the element when obj validation changes', function () {
var obj;
obj = {};
$scope = compile(obj);
$scope.apply(function () {
obj.required = true;
obj.error = true;
});
expect($scope.obj.msg).toContain('fail');
$scope.apply(function () {
obj.required = true;
obj.error = false;
});
expect($scope.obj.msg).toContain('Pass');
$scope.apply(function () {
obj.required = true;
obj.error = "required";
});
expect($scope.obj.msg).toContain('Required');
$scope.apply(function () {
obj.required = false;
obj.error = true;
});
expect($scope.obj.msg).toContain('Pass');
$scope.apply(function () {
obj.required = false;
obj.error = false;
});
expect($scope.obj.msg).toContain('fail');
});
});
我收到错误:
undefined is not an object (evaluating $scopr.apply) error
答案 0 :(得分:0)
您要查找的命令为$scope.$apply()
而不是$scope.apply()
。