Пустой экран ионный

При запуске моего кода я получаю пустой экран с ошибкой консоли:

GET http://localhost/templates/home.html 404 (не найдено)

в результате пустой экран. Код запускается на ламповом сервере (localhost).

Мой index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/index.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <script src="lib/ngCordova/dist/ng-cordova.js"></script>

    <!-- ngRoute error-->
    <script src="lib/angular/angular.js"></script>
    <script src="lib/angular-route/angular-route.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>

    <script src="Scripts/jquery-1.11.2.js"></script>
    <script src="Scripts/URLDecode.js"></script>
    <script src="Scripts/serverInfo.js"></script>
    <script src="Scripts/moment.js"></script>

    <!-- Location of user for displaying nearby restaurants from database
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>-->            


    <!--
    <script>
            localStorage.clear();
    </script>
    -->

  </head>

  <body ng-app="starter">

    <ion-nav-view></ion-nav-view>

    <script id="templates/home.html" type="text/ng-template">
      <ion-side-menus enable-menu-with-back-views="false">
        <ion-side-menu-content>
          <ion-nav-bar class="bar-energized">
          <ion-nav-back-button>
          </ion-nav-back-button>

          <ion-nav-buttons side="left">
              <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
              </button>
          </ion-nav-buttons>

          </ion-nav-bar>
          <ion-nav-view name="sidebarContent"></ion-nav-view>
        </ion-side-menu-content>

        <ion-side-menu side="left">
          <ion-header-bar class="bar-energized">
            <h1 class="title">Testing</h1>
          </ion-header-bar>
          <ion-content>
            <ion-list>
              <ion-item nav-clear menu-close ng-click="startRanging()">
              </ion-item>
            </ion-list>
          </ion-content>
        </ion-side-menu>
      </ion-side-menus>
    </script>

    <script id="templates/rangemodal.html" type="text/ng-template">

    <ion-modal-view>
      <ion-header-bar class="bar-energized">
        <h1 class="title">Beacon values</h1>
        <div class="buttons">
          <button class="button button-clear" ng-click="closeModal()">Close
          </button>
        </div>
      </ion-header-bar>

      <ion-content>
      <ion-refresher spinner="lines" on-refresh="refreshData()">
      </ion-refresher>

      <div class="list">

      <label class="item item-input item-select">
        <div class="input-label">
          Select Major value
        </div>
          <select ng-model="selectedBeacon"
              ng-options="beacon.major for beacon in data">
              <option>--</option>
      </select>
      </label>

      </div>

      <ion-list>
        <ion-item>Minor: {{selectedBeacon.minor}}</ion-item>
        <ion-item>Proximity: {{selectedBeacon.proximity}}</ion-item>
        <ion-item>RSSI: {{selectedBeacon.rssi}}</ion-item>
      </ion-list>

      </ion-content>

    </ion-modal-view>

    </script>

<script id="templates/tester.html" type="text/ng-template">
  <ion-view view-title="tester">
    <ion-content>
      test
    </ion-content>
  </ion-view>
</script>

  </body>

</html>

Внутри моей конфигурации app.js:

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('home', {
    url: "/home",
    abstract: true,
    templateUrl: "templates/home.html",
    controller: 'TestmenuController'
  })
 .state('home.tester', {
 url: "/tester",
 templateUrl: "templates/tester.html",
 controller: 'TestController'

});

$urlRouterProvider.иначе('/тестер');

})

ТесменуКонтроллер:

    .controller('TestmenuController', function($scope, $ionicModal, BeaconData) {

  $scope.data = BeaconData.getData();

  $scope.startRanging = function () {
    BeaconData.startRanging();    
    $scope.data = BeaconData.getData();
  };

  $scope.refreshData = function () {
    //BeaconData.resetData();
    $scope.data = BeaconData.getData();
    $scope.$broadcast('scroll.refreshComplete');
    if($scope.data == '') {
      alert('No data available for region:\n01122334-4556-6778-899a-abbccddeeff0');
    }
  };

  $scope.select = function (major) {
    alert('click');
    $scope.index = data.major.indexOf(major);
    alert(index);
  };

  $ionicModal.fromTemplateUrl('rangemodal.html', {
    scope: $scope,
    animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.openModal = function() {
     $scope.modal.show();
    };
    $scope.closeModal = function() {
        $scope.modal.hide();
    };
    // Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function() {
          $scope.modal.remove();
    });

})

Весь мой app.js

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
ionic.Platform.isReady = true;
angular.module('starter', ['ionic', 'ngCordova', 'ngRoute'])


.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      //StatusBar.styleDefault();
      StatusBar.hide();
    }
    //Put on device's bluetooth
    cordova.plugins.locationManager.isBluetoothEnabled()
      .then(function(isEnabled) {
        if(!isEnabled) {
          cordova.plugins.locationManager.enableBluetooth();
        }
      })
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('home', {
    url: "/home",
    abstract: true,
    templateUrl: "templates/home.html",
    controller: 'TestmenuController'
  })

.state('home.tester', {
url: "/tester",
templateUrl: "templates/tester.html"

});

$urlRouterProvider.иначе('/тестер');

})

.service('BeaconData', function() {

  var data = [];

  this.startRanging = function () {

    var beaconRegion = {

      uuid: '01122334-4556-6778-899a-abbccddeeff0',
      identifier: '89'
    };

    var delegate = new cordova.plugins.locationManager.Delegate();

    cordova.plugins.locationManager.setDelegate(delegate);

    var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(
    beaconRegion.identifier, beaconRegion.uuid);

    /* Every time startRanging() is called, this section will continue to update every split second
    if a beacon is detected for given beaconRegion*/
    delegate.didRangeBeaconsInRegion = function (pluginResult) {

      var result = JSON.stringify(pluginResult);

      var obj = JSON.parse(result);

      for(i = 0; i < obj.beacons.length;i++) {
        data[i] = obj.beacons[i];
      }

    };

    cordova.plugins.locationManager.startRangingBeaconsInRegion(beaconRegion)
    .fail(console.error)
    .done();

  };

  this.resetData = function () {
    data = '';
  }

  this.getData = function () {
    return data;
  };

})

.service('Database', function () {


})
/*
.service('GeolocationService', function() {

  var geocoder;

  this.getLocation = function() {

  geocoder = new google.maps.Geocoder();
  navigator.geolocation.getCurrentPosition(onGetCurrentPositionSuccess, onGetCurrentPositionError);

  var onGetCurrentPositionSuccess = function(position) {
      alert("lat: " + position.coords.latitude);
      alert("long: " + position.coords.longitude);
      var lat = parseFloat(position.coords.latitude);
      var lng = parseFloat(position.coords.longitude);


      var latlng = new google.maps.LatLng(lat, lng);

      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            var arrAddress = results[0].address_components;
            // iterate through address_component array
            $.each(arrAddress, function (i, address_component) {
              if (address_component.types[0] == "locality") {
                console.log(address_component.long_name); // city
                alert(address_component.long_name);
                return false; // break
              }
            });
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }

    var onGetCurrentPositionError = function(error) { 
      console.log("Couldn't get geo coords from device");
    } 
  }
})
*/
.controller('CheckAvailabilityController', function($scope, BeaconData) {


})

.controller('StartController', function($scope, BeaconData) {

})

.controller('TestmenuController', function($scope, $ionicModal, BeaconData) {

  $scope.data = BeaconData.getData();

  $scope.startRanging = function () {
    BeaconData.startRanging();    
    $scope.data = BeaconData.getData();
  };

  $scope.refreshData = function () {
    //BeaconData.resetData();
    $scope.data = BeaconData.getData();
    $scope.$broadcast('scroll.refreshComplete');
    if($scope.data == '') {
      alert('No data available for region:\n01122334-4556-6778-899a-abbccddeeff0');
    }
  };

  $scope.select = function (major) {
    alert('click');
    $scope.index = data.major.indexOf(major);
    alert(index);
  };

  $ionicModal.fromTemplateUrl('rangemodal.html', {
    scope: $scope,
    animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.openModal = function() {
     $scope.modal.show();
    };
    $scope.closeModal = function() {
        $scope.modal.hide();
    };
    // Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function() {
          $scope.modal.remove();
    });
    // Execute action on hide modal
    //$scope.$on('modal.hidden', function() {
    // Execute action
    //});
          // Execute action on remove modal
    //$scope.$on('modal.removed', function() {
          // Execute action
    //});
})

person Thomas    schedule 21.05.2015    source источник
comment
что это <ion-nav-view></ion-nav-view> ??? Я имею в виду: почему он у вас там?   -  person Non    schedule 22.05.2015
comment
у вас есть другая точка зрения? если да, поместите это в свой код, я думаю, я знаю, в чем ваша проблема. Все, что мне нужно, это еще немного информации.   -  person Non    schedule 22.05.2015
comment
Спасибо за ваш комментарий! :) Пока это только мои взгляды. Я попытался имитировать код, найденный здесь: codepen.io/mhartington/pen/azwojR?editors=101.   -  person Thomas    schedule 22.05.2015
comment
попробуйте создать новое представление, а затем здесь: $urlRouterProvider.otherwise('/home/newView');, дайте мне знать, если оно работает, в противном случае я буду здесь, чтобы помочь вам лучше.   -  person Non    schedule 22.05.2015
comment
где именно я должен поместить это новое представление? :с   -  person Thomas    schedule 22.05.2015
comment
Я вижу, вы прокомментировали представление tester, сделайте его представлением. $urlRouterProvider.otherwise('/tester');   -  person Non    schedule 22.05.2015
comment
как и в ссылке Ionic/Codepen, которую вы мне прислали, есть представление .state('app.playlists', {, именно это я и имел в виду.   -  person Non    schedule 22.05.2015
comment
должен ли этот обновленный код работать сейчас?   -  person Thomas    schedule 22.05.2015
comment
не забудьте запустить ionic serve, и вам нужно поместить контроллер в новое представление.   -  person Non    schedule 22.05.2015
comment
Все еще получаю 404 ошибки в консоли браузера. Не удалось загрузить ресурс: сервер ответил со статусом 404 (не найдено)   -  person Thomas    schedule 22.05.2015
comment
подождите, пожалуйста. позвольте мне попытаться сформулировать ваши вещи. не уходи   -  person Non    schedule 22.05.2015


Ответы (3)


Ладно, давайте посмотрим

вот как должен выглядеть ваш html

<html ng-app="ionicApp">
  <head>
    //links and stuff
  </head>

  <body>

    <ion-nav-view></ion-nav-view>

    <script id="templates/home.html" type="text/ng-template">
      <ion-side-menus enable-menu-with-back-views="false">
        ...
      </ion-side-menus>
    </script>

    <script id="templates/tester.html" type="text/ng-template">
      <ion-view view-title="TESTER">
        <ion-content>
          ...
        </ion-content>
      </ion-view>
    </script>
  </body>
</html>

здесь угловая часть

angular.module('ionicApp', ['ionic'])

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

  .state('home', {
    url: "/home",
    abstract: true,
    templateUrl: "templates/home.html",
    controller: 'TestMenuCtrl'
  })

  .state('home.tester', {
    url: "/tester",
    views: {
      'menuContent': {
        templateUrl: "templates/tester.html",
        controller: 'TesterCtrl'
      }
    }
  });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/home/tester');
})

.controller('TestMenuCtrl', function($scope, $ionicModal, $timeout) {
  // Form data for the login modal
  $scope.loginData = {};

})

.controller('TesterCtrl', function($scope) {
  $scope.oneAndtwo = [
    { title: 'one', id: 1 },
    { title: 'two', id: 2 },
    { title: 'three', id: 3 },
    { title: 'four', id: 4 },
    { title: 'five', id: 5 },
    { title: 'six', id: 6 }
  ];
});

а вот рабочий пример http://jsbin.com/diliru/1/edit?html,js,output

не забудьте сделать ionic serve в своем терминале, помните об этом: <ion-nav-view name="menuContent"></ion-nav-view> должно быть тем же именем, которое вы должны указать здесь

  .state('home.tester', {
    url: "/tester",
    views: {
      'menuContent': {
        templateUrl: "templates/tester.html",
        controller: 'TesterCtrl'
      }
    }
  });

не забудьте упомянуть ваши зависимости.

Я не знаю, что еще. Просто дайте мне знать, если я могу помочь.

person Non    schedule 21.05.2015
comment
все еще получаю ту же ошибку 404 :'( большое спасибо за ваши усилия, я полагаю, я должен лучше искать в документах - person Thomas; 22.05.2015
comment
@user3725345 user3725345, как только вы это исправите, вернитесь к этому сообщению и скажите мне, почему это произошло. Приятного аппетита. - person Non; 22.05.2015
comment
@user3725345 user3725345 ответ, который решает вашу проблему, - это ответ. Вы должны дать этому парню лучший ответ. Я думаю, у вас есть еще одна проблема, работающая в фоновом режиме. - person Reacting; 22.05.2015
comment
мой совет: начните новый проект с нуля. - person Non; 22.05.2015
comment
@user3725345 user3725345 хаха здорово :) - person Non; 23.05.2015

Ionic имеет собственный сервер для тестирования вашего приложения. AFIK, он не предназначен для работы в качестве обычного веб-сайта/сервера. Запуск в качестве сервера — это просто инструмент, который они дают для более быстрого создания приложения.

Итак, чтобы запустить приложение,

cd to your app folder

run ionic serve

it should start at localhost:8100 по умолчанию

узнайте больше об их начале работы.

person sameera207    schedule 21.05.2015

Можете ли вы проверить, какую версию Cordova вы используете.

cordova -v 

если версия > 4.3, попробуйте добавить плагин белого списка

ionic plugin add cordova-plugin-whitelist

Новая кордова блокирует http-запрос, и эта ошибка появляется, когда приложение пытается сделать http-запрос.

<access origin="*" />

добавьте источник доступа в файл config.xml.

Это должно решить вашу проблему

person Anshul Kalra    schedule 22.05.2015
comment
добавьте этот плагин, чтобы он работал. ionic plugin add cordova-plugin-whitelist - person Anshul Kalra; 22.05.2015
comment
моя кордова 4.3.0, и я получаю эту ошибку при выполнении команды: npm http GET registry.cordova .io/cordova-plugin-whitelist npm http 404 registry.cordova.io/cordova -plugin-whitelist Ошибка: 404 Not Found: cordova-plugin-whitelist в RegClient.‹anonymous› (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/npm -реестр-клиент/lib/request.js:268:14) - person Thomas; 22.05.2015
comment
попробуйте использовать ионный плагин, добавьте github.com/apache/cordova-plugin-whitelist.git - person Anshul Kalra; 22.05.2015