0

我最近與此範圍內,滑蓋指令嘗試了angularJS在一起我的HTML頁面。但是當我試圖在相應控制器中使用該模型時,我沒有得到實際值,而是在控制器初始化期間設置的初始值。AngularJS 2路結合不更新

controllers.js

app.controller('modelViewCtrl',['$scope','$http','$routeParams', function($scope,$http,$routeParams) { 
 
    $scope.modelId = $routeParams.modelId; 
 
    $scope.timeIntervalStart = new Date().getTime() - (1000*60*60*24*30); 
 
    $scope.timeIntervalEnd = new Date(1452240488000).getTime(); 
 
    $scope.initialIntervalStart = 1452240488000 - (1000*60*60*24*30); 
 
    $scope.initialIntervalEnd = 1452240488000; 
 
    $scope.updateInterval = function() { 
 
    console.log("update: " + $scope.initialIntervalEnd); 
 
    $scope.chosenIntervalStart = new Date($scope.initialIntervalStart); 
 
    $scope.chosenIntervalEnd = new Date($scope.initialIntervalEnd); 
 
    } 
 
    $scope.updateInterval(); 
 
}])

HTML

<div class="panel-heading"> 
 
    {{chosenIntervalStart}} 
 
    <div range-slider 
 
     floor={{timeIntervalStart}} 
 
     step=86400000 
 
     ceiling={{timeIntervalEnd}} 
 
     ng-model-low="initialIntervalStart" 
 
     ng-model-high="initialIntervalEnd"></div> 
 
    {{chosenIntervalEnd}} 
 
</div>

有了這個,我想獲得它們之間滑動的滑塊日期以毫秒爲單位,每日步驟。我正在解析新的Date()對象中已更改的值並希望將其打印出來。

問題是,我總是隻獲得initialIntervalStart/End值而不是滑塊中的實際內容。 但是,當我使用{{initialIntervalEnd}}而不是{{chosenIntervalEnd}}時,當我更改滑塊時,會發生更改值。所以它只在2路數據綁定的一部分進行更新。

我試着用

$scope.$apply(function() { 
    //code to update data 
}); 

和 與$消化相同更新控制器,但沒有奏效。

我也試過在我的控制器,但沒有結果,以及使用觀察者的新變量:

$scope.$watch('initialIntervalStart', function(oldVal,newVal) { 
    //was only once applied, while initial loading the page 
} 

當我使用$消化和$應用,我只能從我的瀏覽器有錯誤。

你知道我該如何強制這種雙向綁定?

親切的問候,

Deleadon

+1

你倒'$ watch'回調函數的參數,它是'的newval,oldVal' – axelduch

回答

1

你應該換你timeIntervalStart中的對象,這樣的角度可以看它,因爲它應該。

請記住,當您需要更新和監視模型時,不應將模型直接綁定到基元。根據指令行爲,您可能不需要此操作,但爲了避免在希望雙向綁定正常工作時發生頭痛,將原始對象包含在範圍內的對象中。

$scope.timer = { 
    timeIntervalStart: new Date().getTime() - (1000*60*60*24*30), 
    timeIntervalEnd: new Date(1452240488000).getTime(), 
    initialIntervalStart: 1452240488000 - (1000*60*60*24*30), 
    initialIntervalEnd: 1452240488000 
}; 

$scope.updateInterval = function() { 
    console.log("update: " + $scope.initialIntervalEnd); 
    $scope.timer.chosenIntervalStart = new Date($scope.timer.initialIntervalStart); 
    $scope.timer.chosenIntervalEnd = new Date($scope.timer.initialIntervalEnd); 
}; 

和HTML

<div class="panel-heading"> 
    {{timer.chosenIntervalStart}} 
    <div range-slider 
     floor={{timer.timeIntervalStart}} 
     step=86400000 
     ceiling={{timer.timeIntervalEnd}} 
     ng-model-low="timer.initialIntervalStart" 
     ng-model-high="timer.initialIntervalEnd"></div> 
    {{timer.chosenIntervalEnd}} 
</div>