sourcecode

각도로 주행뷰 로드 시 JS 초기화 코드

copyscript 2023. 3. 10. 22:41
반응형

각도로 주행뷰 로드 시 JS 초기화 코드

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

그러기 위해 저는 제 뷰의 주요 요소에 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.isSavingflag, 에서 초기화되었습니다.init()기능.

문제: 뷰가 로드되면 isClean 함수가 호출됩니다.init()function, 즉 플래그isSavingundefined어떻게 하면 예방할 수 있을까요?

뷰가 로드되면 연결된 컨트롤러도 로드됩니다.사용하는 대신ng-init전화만 하면 됩니다.init()method를 설정합니다.

$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 함수가 랜덤하게 재실행되지 않습니다.

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

AngularJS 1.5를 사용하면$onInit모든 Angular에서 사용할 수 있습니다.JS 컴포넌트컴포넌트 라이프 사이클 매뉴얼에서 v1.5를 사용하는 것이 바람직합니다.

$onInit() - 요소상의 모든 컨트롤러가 구축되어 바인딩이 초기화된 후(및 이 요소의 디렉티브에 대한 pre 및 post linking 기능 전) 각 컨트롤러에서 호출됩니다.컨트롤러의 초기화 코드를 입력하기 좋은 장소입니다.

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';
    }
});

바이올린 데모

컴포넌트 라이프 사이클의 고급 사용 예:

컴포넌트의 라이프 사이클을 통해 컴포넌트의 내용을 적절하게 처리할 수 있습니다.예를 들어 다음과 같은 이벤트를 생성할 수 있습니다.컴포넌트의 "init", "change" 또는 "internal"입니다.이렇게 하면 컴포넌트의 라이프 사이클에 따라 달라지는 것을 관리할 수 있습니다.이 작은 예에서는, Ethernet 의 등록과 등록을 해제하는 방법을 나타내고 있습니다.$rootScope 리스너 " " "$on 있는 으로써, 을 알 수 있습니다$on 에 묶이다$rootScope.컨트롤러가 되면 언바인드 .$rootScope.$on수동으로 듣습니다.

그 물건을 놓기에 좋은 장소는$onDestroy'CHANGE: 'CHANGE: 'CHANGE: 'CHANGE:

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();
  }
});

바이올린 데모

또는 컨트롤러에서 인라인으로 초기화할 수도 있습니다.컨트롤러 내부에서 init 함수를 사용하는 경우 스코프에서 정의할 필요가 없습니다.실제로 다음과 같은 작업을 직접 수행할 수 있습니다.

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 }
}

프로젝트에서는 다음 템플릿을 사용합니다.

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

반응형