Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable set with ng-init is undefined

I am a beginner in AngularJS (and JS for that matter), and I'm having the following problem.

Here is the html template:

<ion-view view-title="Playlists">
  <ion-content>
    <ion-list>
        <ion-item ng-repeat="playlist in playlists" ng-init="pageID=playlist.id" href="#/app/music/{{playlist.id}}">
            {{playlist.title}} {{pageID}}
        </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

And here is the controller:

.controller('MusicCtrl', function($scope) {
  $scope.playlists = [
    { title: 'Reggae', id: 1 },
    { title: 'Chill', id: 2 },
    { title: 'Dubstep', id: 3 },
    { title: 'Indie', id: 4 },
    { title: 'Rap', id: 5 },
    { title: 'Cowbell', id: 6 }
  ];
  $scope.$watch('pageID', function () {
    console.log($scope.pageID); 
  });

{{pageID}} displays correctly on the page, however in the console, pageID is undefined. What am I doing wrong?

like image 204
Guillaume Avatar asked Jul 01 '26 02:07

Guillaume


1 Answers

pageid is undefined in the console its because you have not defined it in your controller but just assigning value in ng-init. So you may use this inside your controller and then you won't get undefined.

.controller('MusicCtrl', function($scope) {
   $scope.pageID = 1;//just an example
like image 171
Bhojendra Rauniyar Avatar answered Jul 02 '26 15:07

Bhojendra Rauniyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!