ProgramingTip

Cordova + Angularjs + 장치 준비

bestdevel 2020. 12. 31. 23:34
반응형

Cordova + Angularjs + 장치 준비


Cordova와 AngularJS를 사용하여 모바일 애플리케이션을 개발 중입니다. Cordova 장치가 준비되기 전에 AngluarJS의 부트를 제한하는 방법은 무엇입니까? AngularJS 컨트롤러를 사용하기 전에 기본적으로 장치가 준비되기 전에.


Angular 앱을 수동으로 부트합니다.

ng-appHTML 코드에서 속성을 제거 하면 Angular가 자체적으로 시작되지 않습니다.

JavaScript 코드에 다음과 같이 추가하십시오.

document.addEventListener("deviceready", function() {
    // retrieve the DOM element that had the ng-app attribute
    var domElement = document.getElementById(...) / document.querySelector(...);
    angular.bootstrap(domElement, ["angularAppName"]);
}, false);

부트 유효성에 대한 Angular 문서 .


저는 다음 솔루션을 사용하고 있습니다. AngularJS가 Cordova로 실행될 때 뿐만 아니라 대부분의 개발이 브라우저에서 직접 실행될 때 부트 될 수 있습니다 . 수동 부트 교체가 대체되는 것이기 때문에 기본 index.html 페이지에서 ng-app 지시문을 제거해야합니다.

업데이트 : 나는 그 이후로 더 높은 다음 방법으로 전환했습니다. Ionic은 물론 바닐라 Cordova / PhoneGap 작동합니다. 음성 자바 펼쳐의 마지막 비트 . / 몸 태그 앞의 펼쳐 태그 안에있을 수 있습니다 .

  angular.element(document).ready(function () {
    if (window.cordova) {
      console.log("Running in Cordova, will bootstrap AngularJS once 'deviceready' event fires.");
      document.addEventListener('deviceready', function () {
        console.log("Deviceready event has fired, bootstrapping AngularJS.");
        angular.bootstrap(document.body, ['app']);
      }, false);
    } else {
      console.log("Running in browser, bootstrapping AngularJS now.");
      angular.bootstrap(document.body, ['app']);
    }
  });

내가 이전 솔루션은 다음과 가변합니다.

// This is a function that bootstraps AngularJS, which is called from later code
function bootstrapAngular() {
    console.log("Bootstrapping AngularJS");
    // This assumes your app is named "app" and is on the body tag: <body ng-app="app">
    // Change the selector from "body" to whatever you need
    var domElement = document.querySelector('body');
    // Change the application name from "app" if needed
    angular.bootstrap(domElement, ['app']);
}

// This is my preferred Cordova detection method, as it doesn't require updating.
if (document.URL.indexOf( 'http://' ) === -1 
        && document.URL.indexOf( 'https://' ) === -1) {
    console.log("URL: Running in Cordova/PhoneGap");
    document.addEventListener("deviceready", bootstrapAngular, false);
} else {
    console.log("URL: Running in browser");
    bootstrapAngular();
}

웹에서 Cordova 앱을 전화기로로드하여 http / https 감지 방법에 문제가 발생하는 경우 대신 다음 방법을 사용할 수 있습니다.

function bootstrapAngular() {
    console.log("Bootstrapping AngularJS");
    // This assumes your app is named "app" and is on the body tag: <body ng-app="app">
    // Change the selector from "body" to whatever you need
    var domElement = document.querySelector('body');
    // Change the application name from "app" if needed
    angular.bootstrap(domElement, ['app']);
}

// This method of user agent detection also works, though it means you might have to maintain this UA list
if (navigator.userAgent.match(/(iOS|iPhone|iPod|iPad|Android|BlackBerry)/)) {
    console.log("UA: Running in Cordova/PhoneGap");
    document.addEventListener("deviceready", bootstrapAngular, false);
} else {
    console.log("UA: Running in browser");
    bootstrapAngular();
}

첫 번째 예제와 동일한 bootstrapAngular 함수가 여전히 필요합니다.

Cordova / PhoneGap / Ionic으로 AngularJS를 수동으로 부트하는 이유는 무엇입니까?

여기에 오는 일부 사람들은 애초에이 작업을 원하는 이유를 모를 수 있습니다. 문제는 Cordova / PhoneGap / Ionic 플러그인에 의존하는 Angular 제품이 준비되지 않았습니다. 이것은 Cordova가 일반 Javascript 코드보다 장치에서 시작하고 실행하는 데 더 오래 걸리기 때문입니다. AngularJS는 그렇습니다.

따라서 이러한 경우 Angular가 실행에 필요한 모든 것을 갖출 수 있도록 AngularJS를 시작 (부트 스트랩)하기 전에 Cordova / PhoneGap / Ionic이 준비 될 때까지 기다려야합니다.

예를 들어 브라우저에 데이터를 저장하기 위해 로컬 저장소를 사용하는 NG-Persist Angular 모듈, iOS에서 실행할 때 iOS 키 체인 플러그인 , Android에서 실행할 때 cordova-plugin-file을 사용한다고 가정보겠습니다 . Angular 앱이 즉시 무언가를로드 / 저장하려고하면 , 모바일 코드가 아직 시작을 완료하지 않았기 때문에 window.device.platform ( 장치 플러그인에서 ) 에 대한 NG-Persist의 검사 가 실패하고 아무것도 얻지 못할 것입니다. 하지만 예쁜 앱 대신 흰색 페이지입니다.


Ionic 을 사용하는 경우이 솔루션은 브라우저 및 장치에서 작동합니다. 스레드의 romgar 에 대한 크레딧 .

window.ionic.Platform.ready(function() {
    angular.bootstrap(document, ['<your_main_app']);
});

여전히 DOM 요소에서 ng-app을 제거해야합니다.


이 솔루션은 다음을 사용했을 때 더욱 강력 해졌습니다.

angular.element(document).ready(function () {
  var domElement = document.getElementById('appElement');
  angular.bootstrap(domElement, ["angularAppName"]);
});

최신 정보

내 제안은 위의 내용을 적절한 deviceready 기능에 넣는 것입니다. 예 :

document.addEventListener("deviceready", function() {
    angular.element(document).ready(function () {
      var domElement = document.getElementById('appElement');
      angular.bootstrap(domElement, ["angularAppName"]);
    });
}, false);

TheHippo의 솔루션 사용 :

document.addEventListener("deviceready", function() {
    // retrieve the DOM element that had the ng-app attribute
    var domElement = document.getElementById(...) / document.querySelector(...);
    angular.bootstrap(domElement, ["angularAppName"]);
}, false);

"cordova.js"는 Cordova 또는 Phonegap 빌드 프로세스에 의해 해결되고 로컬 호스트 또는 에뮬레이트 된 테스트 환경에서 사용할 수 없기 때문에 브라우저에서 작동하지 않습니다.

따라서 "deviceready"이벤트는 발생하지 않습니다. 브라우저 콘솔에서 수동으로 간단히 실행할 수 있습니다.

var customDeviceReadyEvent = new Event('deviceready');
document.dispatchEvent(customDeviceReadyEvent);

또한 모든 각도 모듈 / 컨트롤러 / 팩토리 / 지시문 등을 설정 한 후 각도의 부트 스트랩이 트리거되는지 확인하십시오.


대부분의 경우 기기 준비가 끝날 때까지 각도 앱로드를 차단할 필요가 없습니다 (플러그인이 많은 경우 deviceready가 실행되는 데 몇 초가 걸릴 수 있음).

대신이 lib ( https://github.com/arnesson/angular-cordova ) 와 같은 것을 사용 하여 자동으로 호출을 버퍼링하여 deviceready 문제를 해결 한 다음 deviceready가 실행 된 후에 실행할 수 있습니다.

참조 URL : https://stackoverflow.com/questions/21556090/cordova-angularjs-device-ready

반응형