ページを最初に読み込んだときに式の自動更新を行う方法を理解するのに問題があります。 JSONオブジェクトを取得して$scope.stocks
に割り当てるサービスを使用しています。 $watch
を使用して、日付スライダー値が更新されるたびに動的に$scope.thisStock
を更新しています。うまくいきます。ただし、ページが最初に読み込まれるとき、$scope.thisStock
は未定義です。私はこれらの問題を解決するための最高の、最もエレガントな方法は何ページの読み込み時に式が自動更新されないのはなぜですか?
:さらに、私は、コンソールでの迷惑なエラーメッセージを取得していますか?非同期呼び出しが解決される前にコントローラが$scope.stocks
を読み込めないようにするにはどうすればいいですか?角度スライダを最初に動かすことなく、できるだけ早くAngularが$scope.thisStock
をロードするように強制するにはどうすればいいですか?ここで
は私のコントローラです:
sim.controller("StocksCtrl", ['$scope', 'StockService', 'DateService',
function($scope, StockService, DateService) {
$scope.init = function() {
$scope.getStocks();
};
$scope.getStocks = function() {
StockService.all().then(function(stocks){
$scope.stocks = stocks;
});
};
$scope.$watch(function() {return DateService.getCurrentDate()}, function(newValue) {
$scope.currentDate = newValue;
$scope.reformatCurrentDate();
});
$scope.reformatCurrentDate = function() {
var arr = $scope.currentDate.split("/");
if (arr[1].length === 1) {
arr[1] = "0" + arr[1];
}
$scope.reformattedCurrentDate = arr[2] + "-" + arr[0] + "-" + arr[1];
};
$scope.$watch('reformattedCurrentDate', function() {
$scope.thisStock = $scope.stocks[$scope.reformattedCurrentDate]["price"];
});
}]);
そしてここでは、HTMLインデックスの関連セクションです:変化検出がreformattedCurrentDate
変数に対して発生したときに
{{thisStock | currency}}