angularjsonsen-uimonaca

how to call function when my (monaca /onsen UI ) start


in my (monaca /onsen UI angularjs ) application I want to load my projects when the project is start

 <script>
    ons.bootstrap()
      .controller('AppController', function() {
        this.pushes = 0;
        this.pops = 0;
        this.details = 0;
        this.showDetails = function(){
            if (this.details == 1)
                this.details = 0;
            else
                this.details = 1;
        }
        this.getProjects = function(){
            console.log('getData');
             $http.get("http://localhost:3000/api/getAllProject")
                .then(function(response) {
            this.projects = response.data;
            console.log('Projects: '+this.projects)

    });
        }
    });
  </script>

and this is the html page

<body ng-controller="AppController as app">
 <ons-sliding-menu
  menu-page="menu.html" main-page="home.html" side="left"
  var="menu" type="reveal" max-slide-distance="260px" swipable="true">
</ons-sliding-menu>
<ons-template id="home.html">
  <ons-navigator var="myNav">
  <ons-page>
    <ons-toolbar>
      <div class="left">
        <ons-toolbar-button ng-click="menu.toggle()">
          <ons-icon icon="ion-navicon" size="28px" fixed-width="false"></ons-icon>
        </ons-toolbar-button>
      </div>
      <div class="center">Projects</div>
      <div class="right">
        <ons-toolbar-button>
            <ons-icon icon="refresh" size="30px" fixed-width="true"></ons-icon>
        </ons-toolbar-button>
      </div>
    </ons-toolbar>

    <ons-list>
        <ons-list-item ng-click="app.showDetails()" ng-repeat="item in app.projects">
              {{item.projectcode}}
        </ons-list-item>
        <div ng-show="app.details==1">
            <p ng-click="myNav.pushPage('level1.html')"> Levels </p>
        </div>
    </ons-list>
  </ons-page>
  </ons-navigator>
</ons-template>

as you can see I need to call the function getProjects() from the AppController when the application start so I can get the projects from DB to display it


Solution

  • There are 3 easy ways to achieve what you want. The differences are minor, but it's best to know them.

    Feel free to choose the method which you think is most relevant for your case.

    Some final notes: