MR.ABC
MR.ABC

Reputation: 4862

AngularJS Where can i access the scope of a loaded controller?

Where can i access the scope of a loaded controller ? I like to have something like a event after the scope has been initialized for a controller to predefine the model for the view.

Is there something like $rootScope.$on("$controllerLoaded")

Upvotes: 1

Views: 261

Answers (2)

Scotty.NET
Scotty.NET

Reputation: 12560

You can do this inside your controller by assigning the value to $scope.

function GreetingCtrl($scope) {
    // a simple string
    $scope.greeting = 'Hola!';

    // something more complex
    $scope.myModel = {id:1, name:'bobby'};
}

You could then use this in your view:

<label>{{myModel.name}}</label>

Which would render a label with 'bobby' inside it (until you change your model and then the view is dynamically updated automagically).

Eventually your application will start to use real world data from a server store of some description and you will need to use either $http or $resource to get at that data. Check each of the links for examples on how to initialise your model from these modules.

Check the Controller documentation for more info

Upvotes: 1

EnigmaRM
EnigmaRM

Reputation: 7632

It's not too clear, but it sounds like you want something to notify another part of an app after a particular controller is loaded. Is that correct?

If so, you have a couple options. Try looking into $emit. Essentially sends a signal to parent listeners.

Here is a write-up of using $emit & $broadcast

$rootScope.$on('emitName', function(){
    //do what you want
});

Another option (more of a hack) would be to set a flag at the end of your controller:

$rootScope.controllerLoaded = true

Then wherever you are wanting to know when it is done, simply check the $rootScope.controllerLoaded flag.

Upvotes: 1

Related Questions