获取X任务的剩余时间,显示如下(不显示none)。 我必须从 -6ren">
gpt4 book ai didi

javascript - AngularJS with Rails 无法识别 $scope

转载 作者:行者123 更新时间:2023-12-03 02:32:30 27 4
gpt4 key购买 nike

我正在 Rails 中开发一个也使用 AngularJS 的项目。首先,我有一个名为 @resource 的变量,其中包含结束时间

<input style="display:none" ng-model="remainingTime" ng-init="remainingTime = <%= (resource.available_until.to_f - DateTime.now.to_f).to_i %>">

获取X任务的剩余时间,显示如下(不显示none)。

A input with a remaining time

我必须从 Controller 访问获得的值。

在 Controller 中我有以下内容:

 function UserEvaluationsNewCtrl ($log, $scope) {
console.log($scope.remainingTime)
}

当我想从 Controller 访问时,变量显示“未定义”:/

任何帮助都是有用的。谢谢!!!

编辑:

console.log($scope): enter image description here

剩余时间=-39698

-负数正确-

编辑2:完整的 Controller :

;(function () {
'use strict';

// Define controller
function UserEvaluationsNewCtrl ($log, $scope) {
$log.debug('UserEvaluationsNewCtrl: Hi')
var vm = this

vm.data = angular.extend({}, rails_data || {})
vm.evaluationData = vm.data.resource
vm.evaluationDataStringified = ''

$scope.$watch(function(){
return vm.evaluationData
}, function(newValue, oldValue){
vm.evaluationDataStringified = angular.toJson(newValue)
$log.debug('ResourcesNewCtrl: $watch vm.evaluationDataStringified: to JSON output:', vm.evaluationDataStringified)
}, true)

console.log($scope)
}

// Inject dependencies
UserEvaluationsNewCtrl.$inject = ['$log', '$scope']

// Register controller
angular
.module('app.controllers.user_evaluations.new', [])
.controller('UserEvaluationsNewCtrl', UserEvaluationsNewCtrl)
})();

最佳答案

原因:在将 remainingTime 变量添加到 $scope 对象之前创建 Controller 。不要相信您的 console.log 对象。

解决方案:

  1. 使用$watch

    $scope.$watch('remainingTime', function() {
    警报($范围.remainingTime);
    });

  2. 或使用$timeout

    $timeout(函数 () {
    警报($范围.remainingTime);
    });

关于javascript - AngularJS with Rails 无法识别 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48674508/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com