【问题标题】:Start and Stop time in javascript + angularjsjavascript + angularjs中的开始和停止时间
【发布时间】:2018-02-09 10:52:51
【问题描述】:

我正在构建员工工作跟踪应用程序,我在 UI 中有一个开始和停止按钮。

我的玉码:

td.table-icon-cell
    a.btn.btn-primary(type='button' href='',ng-click='stop();' ng-if="start.active")
      i.fa.fa-stop(aria-hidden='true')   Stop 
    a.btn.btn-primary(type='button' href='',ng-click='start();' ng-if="!start.active")
       i.fa.fa-clock-o(aria-hidden='true')   Start  

controllers.js:

$scope.start = function () {
    $scope.time = {
        start : moment(new Date()),
        stop : ''
    }
    $scope.start.active = true;
    $http.post('/api/timestart', $scope.time).then(function (response) {
            $scope.savetimes = response.data;
        });
}

$scope.stop = function () {
    $scope.start.active = false;
    $scope.time = {
        start: '',
        stop: moment(new Date())
    }
    $http.post('/api/timestop', $scope.time).then(function (response) {});
}

例如:

我是一名员工,我按下“开始”按钮,然后它变成“停止”按钮,它很好,但如果我加载我的页面,我想要再次“停止”按钮,但它首先显示“开始”。

【问题讨论】:

  • $scope.start.active 的默认值是多少? (你在你的控制器中初始化它吗?)
  • 是的,看看我的代码:我有两种模式,$scope.start.active = true 和 false。
  • 它们仅在您调用以下任一函数时设置:start()、stop()。当您加载您的页面时,是否会触发任何功能?否则$scope.start.active 将是未定义的
  • 是的,怎么写东西?如果用户一旦点击开始,我想在 UI 中显示停止按钮,即使页面加载仍然用户需要再次按下停止。
  • 在你的控制器中,尝试在任何函数之外初始化$scope.start.active = false;

标签: javascript angularjs date time


【解决方案1】:

我认为可能存在两个问题。

首先,您需要初始化您的变量。你可以在你的控制器中写$scope.start.active = false;。例如:

app.controller('your_controller', function($scope, $http) {
  ...
  $scope.start.active = false;
  ...
  $scope.start = function () {...}
  $scope.stop = function () {...}
});

这样,当您重新加载页面时,它的值将始终为false。 (或者你也可以设置成true


其次,我相信你有一个错误。您的函数 start() 与您的变量 start(或$scope.start)同名。这可能会破坏您的 ng-if 逻辑。例如:

start = function(){}
console.log(!start.anything);

在这个例子中(如果你运行它)你会看到,如果你把一个函数当作一个有一些属性的对象,它会返回true,因为!undefined 是真的。

因此,在您的示例中,ng-if="!start.active" 的计算结果为 true,因此它显示 "Start"

要修复它,您只需重命名变量,使它们不再相互匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多