Perform a function while loading the page, JavaScript and Angular

0

I'm doing a registration page, and I need to relate a collaborator to a company, but for this I need when the page loads I already have a companies in a list >

I'm already getting businesses in a list, problem and make the object companies be loaded as soon as the page loads.

This is my Angular function:

  $scope.colaborador = {};
    $scope.empresas = {};

    //Lista todas empresas para cadastro do colaborador
    $scope.getEmpresas = function () {
        var url = "cadastro-colaborador-empresa";
        MainService.get(url).then(function (cb) {
            location.href = 'cadastro-colaborador';
            $scope.empresas = cb;
        });
    };


    $scope.cadastrarColaborador = function () {
        var url = 'cadastra-colaborador';
        MainService.post(url, {colaborador: $scope.colaborador}).then(function (cb) {
            if (cb.idPessoa !== undefined) {
                location.href = 'index';
                $scope.colaborador = {};
                $scope.empresas = {};
            } else {
                $scope.alertaErro = cb;
                $("#myAlert").show();
            }
        });
    };

I'm using vRaptor and Java as well, the function cadastra-colaborador-empresa returns the company list for the business object.

I tried to call the page so <a href="${pageContext.request.contextPath}/administrador/cadastro-colaborador" ng-click="getEmpresas()">Cadastrar Colaborador</a> But it did not work, my select is like this

 <select ng-options="empresa.idEmpresa as empresa.nome for empresa in empresas" ng-model="colaborador.empresa"></select>

The idea is to have the companies loaded in this select, if anyone has an idea how to do it, I'll be grateful.

    
asked by anonymous 12.07.2016 / 15:45

2 answers

2

You can call your function inside the Controller itself, so it will be called as soon as the page opens.

EX:

angular.module('myApp', []);

angular.module('myApp')
  .controller('myCtrl', function($scope) {
    $scope.buscar = function() {
        $scope.nome = 'Nome Teste';
    }
    //Chamando a função buscar
    $scope.buscar();
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp" ng-controller="myCtrl">
 {{nome}}
</div>
    
12.07.2016 / 15:58
0

Try using a tag tag just below your body:

<script>
  document.ready(function(){
    $scope.getEmpresas();
  });
</script>

Although not the only solution:)

    
12.07.2016 / 15:58