Creating and updating the global list with with angularjs in ionic

154 views Asked by At

I try to declare a global list in my ionic project with rootScope variable. My aim is to update this list with specific messages. According to my scenario, I have different views with their forms. I try to hold completed actions in another view in the application. When I press the button of "x" form, "x form is completed" message should be pushed into that global list. After that, when I press the button of "y" form, "y form is completed" message should be appended to that list. Then, I display the content of global list in the completed action view.

In each view, I have a button as shown in screenshot2.

Also, I connected those views with a controller in the controller.js file below:

I created a global list using rootScope for other controllers to reach that list values

 .controller('MainCtrl', function($scope, $rootScope, $state) {

      $rootScope.onButtonClick = function (obj) {
        $rootScope.buttons = [];
        $rootScope.buttons.push(obj); 
        $state.go('app.completed');
    }
 })

Then I connected Completed Actions view with another controller to display the final view of the list to see all pressed buttons in the application:

 .controller('CompletedCtrl', function($scope,$rootScope,$state) {

    $scope.buttons = $rootScope.buttons;

    $scope.onCompletedButtonClick = function(){
    $state.go('app.homepage');  

  }

})

Completed Actions view (html file):


    <span style="color:white">COMPLETED TravelBuddy</span>

 </ion-nav-title>

 <ion-content>

  <div class="list">

  <ion-list>

  <ion-item ng-repeat="item in buttons">
   {{item}}!
  </ion-item>

  </ion-list>

  <label class="item">
      <button class="button button-block button-balanced" ng-click="onCompletedButtonClick()">+</button>
    </label>
</div>

</ion-content>

After I run my mobile application, I can not display all pushed items from the list, I only see the first pressed button message in the completed actions in screenshot1. How could I solve this problem?screenshot1screenshot2

2

There are 2 answers

9
Ram_T On

Working plunker https://plnkr.co/edit/Y2cJrUGYcygvM9i6wKx5?p=preview

  <ion-item ng-repeat="item in buttons track by $index">
   {{item}}!
  </ion-item>

If you want to push duplicates track by $index should be there. Otherwise, you will unable to push, an error will be thrown

Working code

$rootScope.buttons = [];
$rootScope.onButtonClick = function (obj) {
        $rootScope.buttons.push(obj); 
        $state.go('app.completed');
    }

The list will definitely update but if you didn't use ng-repeat="item in buttons track by $index", The above code will throw an error if you push dupes. So, add track by $index to get the desired result

1
Tal Bussel On

You wrote "message should be appended to that list."

but you clean it each time a button is clicked.

move this line out of onButtonClick: rootScope.buttons = [];