0

In angularjs I have a kendo ui drop-down list: in my code, when I click on items in the drop-down list, I remove the selected item and add it to a html table (as a row element):

$scope.optionsDropDownListCatalogs = {
    dataTextField: "Name",
    dataValueField: "Id",
    select: onSelect
};

function onSelect(e) {  
   //Get the selected item
   var item = $scope.dropdownlistCatalogs.dataItem(e.item.index());

   //Remove it from the dropdownlist
   $scope.optionsDropDownListCatalogs.dataSource.remove(item);

   //Add the item in the table datasource
   $scope.products.push(item);
}

In the html page I have a ng-repeat to show the objects inside the $scope.product object.

Sometimes the table is updated, sometimes not. If I put $scope.$apply(); at the end of the function the table is (seems to be) updated correctly.

Why must I execute the $apply()? The push() doesn't happen in the same digest?

Alexey Gorozhanov
  • 706
  • 10
  • 20
Tom
  • 4,007
  • 24
  • 69
  • 105
  • 1
    Just throwing an idea here, but shouldn't the function be part of the scope? Like, `$scope.onSelect = function (e) {...` ? – Jeremy Thille Apr 09 '15 at 12:37
  • http://stackoverflow.com/questions/15475601/ng-repeat-list-in-angular-is-not-updated-when-a-model-element-is-spliced-from-th – Deep Kakkar Apr 09 '15 at 12:40

1 Answers1

0

$apply enables to integrate changes with the digest cycle

You can think of the $apply function as of an integration mechanism. You see, each time you change some watched variable attached to the $scope object directly, Angular will know that the change has happened. This is because Angular already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on. However, sometimes you want to change some value outside of the Angular world and see the changes propagate normally. Consider this - you have a $scope.myVar value which will be modified within a jQuery's $.ajax() handler. This will happen at some point in future. Angular can't wait for this to happen, since it hasn't been instructed to wait on jQuery. To tackle this, $apply has been introduced. It lets you to start the digestion cycle explicitly. However, you should only use this to migrate some data to Angular (integration with other frameworks), but never use this method combined with regular Angular code, as Angular will throw an error then.

How all of this is related to DOM?

Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JS code stays synced, by evaluating every watcher attached to the all $scopes as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished. You can attach objects to the $scope object either explicitly in the Controller, or by declaring them in {{expression}} form directly in the view.

SRC: READ THIS

Community
  • 1
  • 1
Ved
  • 11,837
  • 5
  • 42
  • 60