Question

I'm beginner in AngularJS and I want to create a controller to each view, but this file only can be referenced when I load the view, so:

my app.js:

var app = angular.module('app',['ngRoute']);

app.config(function($routeProvider)
{
    $routeProvider
    .when('/', { 
        templateUrl : 'app/views/login.html'
    })
    .when('/calendar', {
        templateUrl : 'app/views/calendar.html'
    })
    .otherwise ({ redirectTo: '/' });
});

app.run( function($route, $rootScope, $location)
{
    $rootScope.$on( "$routeChangeStart", function() 
    {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = load_script($location.path());
        document.body.appendChild(s);
    });
});

function load_script(location) 
{
    switch(location)
    {
        case '/'            : return 'app/controllers/loginController.js';
        case '/calendar'    : return 'app/controllers/calendarController.js';
    }
}

And in the view I set the name of the controller and put a directive to test:

<h1>Página login!</h1>

<div ng-controller="loginCtrl">
    <p ng-bind="teste"></p>
</div>

In controller I set:

app.controller('loginCtrl', function($scope)
{
    $scope.teste = 'loginCtrl';
});

I did this but the value of $scope.teste don't change. How can I solve this problem?

Was it helpful?

Solution

Your adding your script to your page, but you have no clue when it is actually fetched and parsed. It could be waiting for the server or not be parsed in time for Angular to register it before calling it. You would have to set a deffered and manage callbacks for when your script it loaded and resolve promises to let angular know when everything is good to continue. Its a bit more work.

Also since your app is already loaded, you would need to use $controllerProvider.register to register your controller after the fact.

If you don't want to do the work (I would only recommend doing it yourself as a way to learn how it all works), there are tons of solutions for what you are trying to attempt. Try looking around for "angularjs lazy load" or check out this: https://github.com/nikospara/angular-require-lazy

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top