Running AngularJS initialization code when view is loaded

后端 未结 4 1963
情书的邮戳
情书的邮戳 2020-11-29 00:22

When I load a view, I\'d like to run some initialization code in its associated controller.

To do so, I\'ve used the ng-init directive on the main element of my view

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 00:33

    When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

    $scope.init = function () {
        if ($routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
        $scope.isSaving = false;
    }
    ...
    $scope.init();
    

    Since your controller runs before ng-init, this also solves your second issue.

    Fiddle


    As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

    var init = function () {
        // do something
    }
    ...
    init();
    

    See jsFiddle


    If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

    var init = function () {
        // do something
    }
    ...
    var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                        if( newVal && newVal.length > 0) {
                            unwatch();
                            init();
                        }
                    });
    

提交回复
热议问题