Angular JS双向绑定不起作用

时间:2015-04-28 15:16:07

标签: javascript angularjs html5 angularjs-ng-repeat angularjs-ng-model

我无法在控制器中使用双向绑定。有些奇怪但我不明白。我的数据结构是一个包含字符串数组的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>

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

1 个答案:

答案 0 :(得分:0)

您可能会从angular angular范围内调用showSchedules()函数。您需要通过将函数体包装在$scope.$apply(...)

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

您也可以在showSchedules来电中将来电置于$scope.$apply(...)