简体   繁体   中英

Angular JS two-way-binding doesn't work

I am not able to use two-way-binding in my controller. There is something strange but I don't understand it. My data structure is a javascript object containing an array of strings.

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

I retrieve the schedules from my database and place it in a list in the UI. The elements of the $scope.scheduleList are clickable. If the user clicks on a schedule element then it will appear on the screen with all properties of the schedule object.

I iterate over the dates array with ng-repeat="date in schedule.dates" and use the date-value in ng-model="date.date" like this.

My Problem is that the scope variable schedule won't be updated on any changes. Here is an excerpt of my code:

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

I am very lucky if anyone could help me! Thanks in advance!

You are likely calling the showSchedules() function from outside angular's scope. You need to tell angular to update the bindings by wrapping the function body in $scope.$apply(...) :

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

You could wrap the call to showSchedules in a $scope.$apply(...) call as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM