Programing

뷰가로드 될 때 AngularJS 초기화 코드 실행

lottogame 2020. 9. 13. 11:34
반응형

뷰가로드 될 때 AngularJS 초기화 코드 실행


뷰를로드 할 때 연결된 컨트롤러에서 일부 초기화 코드를 실행하고 싶습니다.

이를 위해 뷰의 주요 요소에 ng-init 지시문을 사용했습니다.

<div ng-init="init()">
  blah
</div>

컨트롤러에서 :

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

    $scope.isSaving = false;
}

첫 번째 질문 : 이것이 올바른 방법입니까?

다음으로, 발생하는 사건의 순서에 문제가 있습니다. 보기에는 다음 ng-disabled과 같은 지시문 을 사용하는 '저장'버튼이 있습니다 .

<button ng-click="save()" ng-disabled="isClean()">Save</button>

isClean()기능은 제어기에 정의 :

$scope.isClean = function () {
    return $scope.hasChanges() && !$scope.isSaving;
}

보시다시피 함수 $scope.isSaving에서 초기화 된 플래그를 사용합니다 init().

문제 : 뷰가로드 될 때 isClean 함수 호출 전에init() 따라서 플래그, 함수 isSaving이다 undefined. 이를 방지하려면 어떻게해야합니까?


뷰가로드되면 연관된 컨트롤러도로드됩니다. 을 사용하는 대신 컨트롤러에서 메서드를 ng-init호출하기 만하면 init()됩니다.

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

컨트롤러가 이전 ng-init실행되기 때문에 두 번째 문제도 해결됩니다.

깡깡이


으로 John David Five언급, 당신은이를 첨부하지 않을 수 있습니다 $scope이 방법은 비공개로하기 위해.

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

jsFiddle 참조


특정 데이터가 사전 설정 될 때까지 기다리려면 해당 데이터 요청을 해결로 이동하거나 해당 컬렉션 또는 개체에 감시자를 추가하고 데이터가 초기화 기준을 충족 할 때 init 메서드를 호출합니다. 일반적으로 데이터 요구 사항이 충족되면 감시자를 제거하므로보고있는 데이터가 변경되고 init 메서드를 실행하기위한 기준을 충족하는 경우 init 함수가 무작위로 다시 실행되지 않습니다.

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

Since AngularJS 1.5 we should use $onInit which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {

    //default state
    $scope.name = '';

    //all your init controller goodness in here
    this.$onInit = function () {
      $scope.name = 'Superhero';
    }
});

>> Fiddle Demo


An advanced example of using component lifecycle:

The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope event listener $on. By knowing, that an event $on binded on $rootScope will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on listener manually. A good place to put that stuff is $onDestroy lifecycle function of an component:

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

myApp.controller('MyCtrl', function ($scope, $rootScope) {

  var registerScope = null;

  this.$onInit = function () {
    //register rootScope event
    registerScope = $rootScope.$on('someEvent', function(event) {
        console.log("fired");
    });
  }

  this.$onDestroy = function () {
    //unregister rootScope event by calling the return function
    registerScope();
  }
});

>> Fiddle demo


Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

I use the following template in my projects:

angular.module("AppName.moduleName", [])

/**
 * @ngdoc controller
 * @name  AppName.moduleName:ControllerNameController
 * @description Describe what the controller is responsible for.
 **/
    .controller("ControllerNameController", function (dependencies) {

        /* type */ $scope.modelName = null;
        /* type */ $scope.modelName.modelProperty1 = null;
        /* type */ $scope.modelName.modelPropertyX = null;

        /* type */ var privateVariable1 = null;
        /* type */ var privateVariableX = null;

        (function init() {
            // load data, init scope, etc.
        })();

        $scope.modelName.publicFunction1 = function () /* -> type  */ {
            // ...
        };

        $scope.modelName.publicFunctionX = function () /* -> type  */ {
            // ...
        };

        function privateFunction1() /* -> type  */ {
            // ...
        }

        function privateFunctionX() /* -> type  */ {
            // ...
        }

    });

참고URL : https://stackoverflow.com/questions/16150289/running-angularjs-initialization-code-when-view-is-loaded

반응형