angularjs 拆分字符串时解析语法错误

angularjs parse syntax error when splitting a string

我有一个指令将 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].

我在我的一个 ionic 项目中使用了相同的代码,它运行良好,但是转移到 angularjs v1.2.28 却让我很头疼。请帮助

使用 scope: {timeset='='}(称为 isolateBinding),我们为 timeset 指定的属性值将被视为在范围内定义的变量名。

由于 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>";

阅读更多关于 angular isolateBindings 的信息:https://docs.angularjs.org/guide/directive

您可以按照@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;
            }
            [...]
        }
   };
});

虽然不是很漂亮...