Angular JS 双向绑定不起作用

Angular JS two-way-binding doesn't work

我无法在我的控制器中使用双向绑定。有一些奇怪的东西,但我不明白。我的数据结构是一个包含字符串数组的 javascript 对象。

$scope.schedule = {
    schedule_name: "Test 123",
    schedule_id: 1234,
    dates: [{
        date: "2015-01-01"
    }, {
        date: "2015-02-01"
    }, {...}]
}

我从我的数据库中检索时间表并将其放入 UI 的列表中。 $scope.scheduleList 的元素是可点击的。如果用户单击一个日程表元素,那么它将出现在屏幕上,其中包含日程表对象的所有属性。

我用 ng-repeat="date in schedule.dates" 遍历日期数组并像这样使用 ng-model="date.date" 中的日期值。

我的问题是范围变量 schedule 不会根据任何更改进行更新。 这是我的代码的摘录:

$scope.scheduleList = [];
CommonDataService.get(URL).then(function(data) {
  for (var i = 0; i < data.length; i++) {
    data[i].dates.forEach(function(value, key) {
      data[i].dates[key] = {date: $filter("date")(value, "EEE, dd.MM.yyyy")};
    });
    data[i].schedule_name = data[i].schedule_name.substr(4);
  }
  $scope.scheduleList = data;
});

$scope.schedule = {};
$scope.showSchedules = function(schedule) {
    $scope.schedule = schedule;
}

...

$scope.save = function() {
  console.log($scope.schedules);
  //CommonDataService.add(URL, $scope.schedules).then(function(response) {
  //    console.log(response);
  //});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<body data-ng-app="rwk">
...
    <div class="form-group col-lg-6" data-ng-repeat="date in schedule.dates track by $index" data-ng-if="key !== 'schedule_id' && key !== 'schedule_name'">
      <div class="col-lg-9">
        <p class="input-group pull-left">
          <input data-rwk-datepicker data-format="D, dd.mm.yyyy" id="{{$index}}" type="text" class="form-control" data-ng-model="date.date" data-ng-required="true" />
        </p>
      </div>
    </div>
</body>

如果有人能帮助我,我很幸运! 提前致谢!

您可能是从 angular 的范围之外调用 showSchedules() 函数。您需要告诉 angular 通过将函数体包装在 $scope.$apply(...):

中来更新绑定
$scope.schedule = {};
$scope.showSchedules = function(schedule) {
    $scope.$apply(
        $scope.schedule = schedule;
    );
}

您也可以将对 showSchedules 的调用包装在 $scope.$apply(...) 调用中。