数字0在javascript中等于false,如何修复我的代码

时间:2014-11-08 02:11:54

标签: angularjs filter

我练习了书籍Pro AngularJS中的示例代码,如下所示:

我测试过,如果index0now.GetDay(),则会出现错误,例如,今天是星期日,因此0返回0。然后视图会认为falseunknown,显示Module Value - days.today = nowValue.getDay() + 1而不是读取日变量并跟随过滤器过程。

我想问一下解决这个问题的最佳/优雅方法是什么,以确保星期日案例能够正常运作。

我认为一种方法是0,所以避免index大小写,然后在过滤器中,当使用<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!DOCTYPE html> <html ng-app="exampleApp"> <head> <title>AngularJS Demo</title> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script src="angular.js"></script> <script> var myApp = angular.module("exampleApp", []); myApp.controller("dayCtrl", function ($scope,days) { $scope.day = days.today; }); myApp.controller("tomorrowCtrl", function ($scope, days) { $scope.day = days.tomorrow; }); myApp.directive("highlight", function ($filter) { var dayFilter = $filter("dayName"); return function (scope, element, attrs) { if (dayFilter(scope.day) == attrs["highlight"]) { element.css("color", "red"); } } }); myApp.filter("dayName", function () { var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; return function (input) { return angular.isNumber(input) ? dayNames[input] : input; }; }); var now= new Date(); myApp.value("nowValue", now); myApp.service("days", function (nowValue) { this.today = nowValue.getDay(); this.tomorrow = (this.today + 1) ; }); </script> </head> <body> <div class="panel"> <div class="page-header"> <h3>AngularJS App</h3> </div> <h4 ng-controller="dayCtrl" highlight="Saturday"> Today is {{day || "(unknown)" | dayName}} </h4> <h4 ng-controller="tomorrowCtrl"> Tomorrow is {{day || "(unknown)" | dayName}} </h4> </div> </body> </html>来读取数组时减去1。

{{1}}

2 个答案:

答案 0 :(得分:1)

我想说过滤器的实现是这里的问题,因为以下行

{{day || "(unknown)" | dayName}}

这里,当天为0时,它是一个虚假的&#39;价值等等,&#34; ||&#34;运算符返回第二个表达式,即&#34;(未知)&#34; 找到当天名字的责任,如果应该在过滤器中,我建议您将过滤器编写为:

myApp.filter("dayName", function () {
    var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    return function (input) {
        // you don't have to check if it is a number, 
        // if you don't pass a valid value, undefined is returned anyways
        var dayName = dayNames[input] || "(unknown)";
    };
});

你可以使用这个过滤器     {{day | DAYNAME}}

一个重要的收获是,不要在多个地方分配一个责任,如果当天的名字是过滤器的责任,找到默认名称也应该。这导致错误修复,添加功能和新更改的单一维护点。

答案 1 :(得分:0)

这对我有用:

myApp.filter("dayName", function () {
    var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"];
    return function (input) {
        input = (input > 6) ? 0 : input;
        return angular.isNumber(input) ?  dayNames[input] : input;
    };
});