Question

I need to execute a function which is defined in controller in load-time, in order to gain json data from another place right after page is loaded.
I've tried to call the func immediately within controller, now i feel it was bad idea.
When something bad is happen and exception is raised - the controller stops working.

Well, not big surprise, but at the moment i don't have idea how work it out.
Ofcourse, i can wrap possible dangerous code in try-catch, but that's definetely not best solution imho.
Here's the sample code:

app.controller("ServerStatusCtrl",
    function($scope) {
        $scope.reloadFunc = function()
        {
            throw "dat bad exception";
        }
        $scope.reloadFunc(); // Let's pretend that it's needed 2 call this function in load-time.
    });

And example on jsfiddle

Was it helpful?

Solution 2

Found easier solution for this.
Just discovered a ngInit directive which solved the whole problem.
Also, i think that module.run(fn) would be also applicable for this kind of tasks.

OTHER TIPS

I advice you to use $q's way of notifying that something happen: return promise and reject it after something wrong happen.

This is the way how exception handling is done in async/promise way.

General idea is:

  1. Instead of returning result, function should return promise
  2. When you have your data ready (loaded from server) you resolve promise
  3. If something bad happen you reject it.

    function someFunc() { var d = $q.defer(); do.somethingAsync(function(result) { if (somethingWrong) d.reject(result); else d.resolve(result); }); return d.promise; }

And in controller:

   $scope.myData = someFunc().then(function ok(result) { return ok.data; }, function faled() { handle...});

This gives a good control on error handling/recovery.

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