iamawebgeek
iamawebgeek

Reputation: 2865

How to run controller code after scope is compiled

I have a router which runs my controller when I go to url: #/create. I have configured it like so:

$routeProvider
    .when("/create", {
        templateUrl: "templates/create",
        resolve: {
            form: function () {
                return { fields: [] };
            }
        },
        controller: "createController"
    })

And inside this controller I load some of my components asynchroniously inside my services and assign it to the respective scope property.

.controller(function ($scope, service /* other components */) {
    // code
    console.log($scope); // sometimes it gives $rootScope
    service.get().load([["forms"]], $scope); // the reaso I am passing the scope is that my service could assign loaded data to it
})

Sometimes when I refresh the page I have request for modules, but I do not have them assigned to the scope. After lots of debugging I have found out the problem. I am running into trouble when template is not compiled and instead of $scope I am getting $rootScope, so I get modules assigned to other/incorrect scope. The question here is, how can I run my controller code after the scope is compiled?

Upvotes: 0

Views: 52

Answers (2)

brewsky
brewsky

Reputation: 617

You should be using a promise to resolve your data. When you call the server to get the data, it is a asynchronous operation. Typically, the service returns a promise. You assign your data when the promise is resolved.

 service.get().success( function(data,status,headers){
       $scope.something = data;
 });

Upvotes: 0

Yoann Prot
Yoann Prot

Reputation: 524

You should never have $rootScope instead of the controller scope. I think something is not configured correctly. You should check that you :

  • give a name to your controller (I don't see it in your example)
  • don't have any ng-controller on your html code that could call the controller
  • never try to create it directly in JS code

In another hand, you should not give $scope to your service. It is better to use callback instead.

You could change your controller accordingly :

/* resolve values should be inject */
.controller("createController", function ($scope, service, form) {
    $scope.form = form;

    service.get().load(function(value) {
        $scope.someValues = value;
    });
})

Upvotes: 1

Related Questions