AngularJS 2 向绑定未更新

AngularJS 2-way-binding not updating

我最近尝试了 angularJS 和这个范围滑块指令:

https://github.com/supertorio/angular-rangeslider-directive

当我仅在我的 HTML 页面中使用数据模型时,使用描述的方法工作正常。但是当我试图在相应的控制器中使用模型时,我没有得到实际值,而是我在控制器初始化期间设置的初始值。

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 向数据绑定的 1 部分上更新。

我尝试用

更新控制器
$scope.$apply(function() {
  //code to update data
}); 

和 与 $digest 相同,但它没有用。

我也尝试在控制器中的新变量上使用观察器,但也没有结果:

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

当我使用 $digest 和 $apply 时,我只从我的浏览器中得到错误。

你知道我如何强制这个双向绑定吗?

亲切的问候,

Deleadon

您应该将 timeIntervalStart 包裹在一个对象中,以便 angular 可以按预期观看它。

请记住,当您需要更新和监视模型时,不应将模型直接绑定到图元。根据指令行为,您可能不需要它,但为了避免在您期望 2 路绑定正常工作时头疼,请将基元包装在范围内的对象中。

$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>