我有一个指令,它将mysql日期时间字符串替换为月份和日期。但它给了我解析语法错误。
指令:
directiveApp.directive('cleanDate',function(){
var monthName = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"];
return {
restrict: 'AE',
template: '{{mon}} {{date}}',
scope: {
timeset: '='
},
link: function(scope, element, attr) {
console.log(scope.timeset);
var t = scope.timeset.split(/[- :]/);
console.log(t);
if (parseInt(t[0]) != 0 && parseInt(t[1])!=0 && parseInt(t[2])!=0){
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
scope.mon = monthName[d.getMonth()];
scope.date = d.getDate();
}
else{
scope.mon = '';
scope.date='';
}
}
};
指令测试:
describe('getDistance Directive',function(){
var $scope,$compile,template;
beforeEach(inject(function(_$compile_, _$rootScope_){
$scope = _$rootScope_;
$compile = _$compile_;
}));
it ('Check Clean Date',function(){
var element = "<clean-date timeset='2015-01-20 11:17:32'></clean-date>";
template = $compile(element)($scope);
$scope.$digest();
expect(template.html()).toBe('January 20');
});
});
但是这个测试用解析语法错误
响应Error: [$parse:syntax] Syntax Error: Token '11' is an unexpected token at column 12 of the expression [2015-01-20 11:17:32] starting at [11:17:32].
我在我的一个离子项目中使用相同的代码并且工作正常,但转移到angularjs v1.2.28让我头疼。请帮忙
答案 0 :(得分:1)
使用scope: {timeset='='}
(称为isolateBinding),我们为timeset
指定的属性值将被视为范围中定义的variableName。
由于2015-01-20 11:17:32
不是有效的javascript变量名,解析器会抛出错误。
我们应该如何使用:
//define a scope variable
$scope.time = "2015-01-20 11:17:32";
var element = "<clean-date timeset='time'></clean-date>";
详细了解角度isolateBindings:https://docs.angularjs.org/guide/directive
答案 1 :(得分:0)
您可以像@ vinay-k所建议的那样,或者您可以更改您的指令以使用属性值而不是数据绑定(因为您只使用该值来初始化您的指令):
directiveApp.directive('cleanDate',function(){
[...]
return {
[...]
scope: {
timeset: '@'
},
[...]
};
});
然后你可以像这样使用它:
<clean-date timeset="2015-01-20 11:17:32"></clean-date>
<clean-date timeset="{{timeVarFromScope}}"></clean-date>
或者你可以使用$ scope.eval进一步接受它们!例如:
directiveApp.directive('cleanDate',function(){
[...]
return {
scope: {
},
link: function(scope, element, attr) {
try {
scope.timeset = scope.$eval(attr.timeset);
} catch (e) {
scope.timeset = attr.timeset;
}
[...]
}
};
});
虽然那不是很漂亮......