Ionic Controller and Service Structure - angularjs

I'm pretty new to Ionic and AngularJS. I tried to create a note app but my controllers.js did not seem to understand services.js. What do I have to do to fix this problem. Thanks in advance.
And this is my code look like
app.js
(function() {
var app = angular.module('starter', ['ionic', 'starter.controllers' ,'starter.services'])
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('list', {
url: '/list',
templateUrl : 'templates/list.html'
});
$stateProvider.state('edit', {
url: '/edit/:Id',
templateUrl : 'templates/edit.html',
controller : 'EditCtrl'
});
$stateProvider.state('add', {
url: '/add',
templateUrl : 'templates/edit.html',
controller : 'AddCtrl'
});
$urlRouterProvider.otherwise('/list');
});
app.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();
}
});
})
}());
controllers.js
angular.module('starter.controllers', [])
.controller('ListCtrl', function($scope, NoteStore) {
$scope.notes = NoteStore.list();
});
.controller('EditCtrl', function($scope, $state, NoteStore) {
$scope.title = "Edit";
$scope.note = angular.copy(NoteStore.get($state.params.Id));
$scope.save = function() {
NoteStore.update($scope.note);
$state.go('list')
};
});
.controller('AddCtrl', function($scope, $state, NoteStore) {
$scope.title = "New Note";
$scope.note = {
id: new Date().getTime().toString()
};
$scope.save = function() {
NoteStore.create($scope.note);
$state.go('list')
};
});
services.js
angular.module('starter.services', [])
.factory('NoteStore', function() {
var notes = [];
return {
list : function() {
return notes;
},
get : function(noteId) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].id === noteId) {
return notes[i];
}
}
return undefined;
},
create : function(note) {
notes.push(note);
},
update : function(note) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].id === note.id) {
notes[i] = note;
return;
}
}
return undefined;
}
}
});
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">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-nav-bar class="bar-assertive">
<ion-nav-back-button class="button-clear">
<i class="ion-arrow-left-c"></i> Back
</ion-nav-back-button>
</ion-header-bar>
<ion-nav-view>
</ion-nav-view>
</ion-pane>
</body>
</html>
list.html
<ion-view view-title="My Notes">
<ion-nav-buttons side="right">
</ion-nav-buttons>
<ion-content ng-controller="ListCtrl">
<div class = "list">
<a href="#/edit/{{note.id}}" class = "item" ng-repeat = "note in notes">
<h2>{{note.title}}</h2>
<p>{{note.description}}</p>
</a>
</div>
</ion-content>
</ion-view>
edit.html
<ion-view view-title="{{title}}">
<ion-content>
<div class="list card">
<div class="item item-input">
<input type="text" placeholder="Title" ng-model="note.title">
</div>
<div class="item item-input">
<textarea rows="5" placeholder="Description" ng-model="note.description"></textarea>
</div>
</div>
<div class="padding">
<button class="button button-positive button-block" ng-click="save()">Save</button>
</div>
</ion-content>
</ion-view>

When you separate it into separate files first make sure you load the files in your index.html
so for each controller or service js file you will need in your index.html
<script type="text/javascript" src="//path to js file"></script>
The next thing you need to do is inject your services and your controller into your main app.module which you did do here:
var app = angular.module('starter', ['ionic', 'starter.controllers' ,'starter.services'])
You also need to inject your service into you controller which you did not do so in
angular.module('starter.controllers', [])
you need to inject 'stater.services'
so it should look like
angular.module('starter.controllers', ['starter.services'])
then in your controller you can inject whatever factory you need
.controller('EditCtrl', function(NoteStore){})
each module needs to have the other modules it depends on injected into it.
For example on my app i also inject ionic into my controllers and services.
That should get it working for you. If you want me to post more examples let me know.

Found the problem!!!
In the controllers.js you can't end a controller and start another.
If you want to use multiple controllers on the same JS file, you have to use semicolon only on the last controller.
I.E. You have 3 controllers
.controller('ListCtrl', function(){})
.controller('EditCtrl', function(){})
.controller('AddCtrl', function(){});
Only the last controller have to end with semicolon.

Related

When clicking very quickly on Angularjs app page doesn't load

FYI - I am very new to Angular...not my code mostly from tutorial on Lynda which I am playing with.
I noticed when I am doing a type of "pagination" where I am showing different elements from a data.json file, the page doesn't load if I click page back anchor links too quickly to show the next or previous item. The culprit begins somewhere as a result of the anchor tags here (details.html file) / in the controller of details. I am wondering if it's async/await not being used issue.
<div class="container">
<div class="row">
<div class="col-12 mt-3">
<div class="card">
<div class="card-header d-flex align-items-start justify-content-between">
<h1 class="card-title my-0">{{artists[whichItem].name}}</h1>
<nav class="btn-group">
<a class="btn btn-sm btn-secondary"
href="#/details/{{prevItem}}"><</a>
<a class="btn btn-sm btn-secondary"
href="#/">•Home</a>
<a class="btn btn-sm btn-secondary"
href="#/details/{{nextItem}}">></a>
</nav>
</div>
<div class="card-body"
ng-model="artists">
<h4 class="card-title text-dark mt-0">{{artists[whichItem].reknown}}</h4>
<img class="float-left mr-2 rounded"
ng-src="images/{{artists[whichItem].shortname}}_tn.jpg"
alt="Photo of {{artists[whichItem].name}}">
<div class="card-text text-secondary">{{artists[whichItem].bio}}</div>
</div>
</div>
</div>
</div>
</div>
In the meantime - By searching different things online I added a
.otherwise({
redirectTo: '/'
});
a redirect so something shows up. It'd be great if someone can please help explain what's causing that and how to fix it. I am posting the code below. I also added console.logs to help me debug in my controller, but I was not successful.
My smaller controller - (controllers.js):
var myControllers = angular.module('myControllers', []);
myControllers.controller('SearchController', function MyController($scope, $http) {
$scope.sortArtistBy = 'name';
$http.get('js/data.json').then(
(response) => $scope.artists = response.data
);
});
myControllers.controller('DetailsController', function MyController($scope, $http, $routeParams) {
$http.get('js/data.json').then(
function(response) {
$scope.artists = response.data
$scope.whichItem = $routeParams.itemId;
if($routeParams.itemId > 0){
$scope.prevItem = Number($routeParams.itemId) - 1;
console.log("I am going to 18")
} else {
console.log("I am going to 20")
$scope.prevItem = $scope.artists.length - 1;
}
if($routeParams.itemId < $scope.artists.length - 1){
console.log("I am going to 25")
$scope.nextItem = Number($routeParams.itemId) + 1;
} else {
console.log("I am going to 28")
$scope.nextItem = 0;
}
}
);
});
My main app controller (app.js):
var myApp = angular.module('myApp', [
'ngRoute',
'myControllers'
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'js/partials/search.html',
controller: 'SearchController'
})
.when('/details/:itemId', {
templateUrl: 'js/partials/details.html',
controller: 'DetailsController'
})
.otherwise({
redirectTo: '/'
});
}]);
My (index.html) file:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="lib/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body class="bg-secondary">
<div ng-view></div>
<script src="lib/jquery/jquery.min.js"></script>
<script src="lib/bootstrap/popper.min.js"></script>
<script src="lib/bootstrap/bootstrap.min.js"></script>
</body>
</html>
One approach is to cache the data in a service:
app.service("dataService", function($http) {
var cache;
this.get = () => {
cache = cache || $http.get('js/data.json');
return cache;
};
})
Then in the controller:
app.controller('DetailsController', function MyController($scope, dataService, $routeParams) {
dataService().then(
function(response) {
$scope.artists = response.data
$scope.whichItem = $routeParams.itemId;
//...
}
);
});
By caching the $http promise, the app avoids repeating identical requests to the server.

Angular loading Controllers and Services

I am using Angularjs for my application.I am having one common page which has header and footer which i am making common for all pages.Thats y i am placing it in one common html.Only contents code i am placing in other html pages.
As i am using one common page i am loading all controllers and all Services that i am using in the application.
Here is my commonpage.html
<!DOCTYPE html>
<html lang="en" data-ng-app="adminApp">
<head>
</head>
<body>
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="resources/angular/controller/admin/AdminExamController.js">
</script>
<script src="resources/angular/service/admin/AdminExamService.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
The doubt i am having is,is it necessary to place all controllers and services like i am doing because i am facing performance issue even though i am connected to strong internet it loads very slow.As i am placing all in one page it is loading all controllers and services everytime.If i place controllers in their respective html then i am getting error like ExamController.js or any .js Controller not defined.Is there any other way that i can load all controllers and services so that i can increase the performance of the application?
I think this is what your looking for
app.js
/* Module Creation */
var app = angular.module ('adminApp', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function () { result.reject(); };
document.querySelector("head").appendChild(script);
return result.promise();
}
function loader(arrayName){
return {
load: function($q){
var deferred = $q.defer(),
map = arrayName.map(function(name) {
return loadScript(name+".js");
});
$q.all(map).then(function(r){
deferred.resolve();
});
return deferred.promise;
}
};
}
$routeProvider
.when('/view2', {
templateUrl: 'view2.html',
resolve: loader(['Controller2'])
})
.when('/bar',{
templateUrl: 'view1.html',
resolve: loader(['Controller1'])
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
</head>
<body ng-app="adminApp">
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="app.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
Controller 1.js
(function(val){
'use strict';
angular.module('Controller1App', [])
.controller('Controller1', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Controller 2.js
(function(val){
'use strict';
angular.module('Controller2App', [])
.controller('Controller2', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Refer https://plnkr.co/edit/cgkgG5PCwJBVOhQ1KDW2?p=preview

Why do I keep getting the $[injector:modulerr] uncaught error when all dependencies have been injected?

Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.
Below is my
HTML
<!DOCTYPE html>
<html>
<head>
<title>PR_APP</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<script src="js/main.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="new_pr_app">
<h2>Please select an option</h2><br>
<div ng-controller="view_controller">
<button id="view_details" ng-click="view()">View Details</button>
</div>
<div ng-controller="update_controller">
<button id="update_details" ng-click="update()">Update Details</button>
</div>
<div ng-view>
</div>
</body>
Below is my main.js file which houses both above mentioned controller and logic for angular routing.
main.js
var app = angular.module('new_pr_app', ['ngRoute']);
app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
templateUrl:"update.html",
controller: "update_controller"
})
.when("/view",
{
templateUrl: "view.html",
controller: "view_controller"
});
});
app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
$location.path("/view");
}
$scope.result =[];
http_factory.get_request().then(function(response){
$scope.result = response.data;
});
});
app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
$location.path("/update");
}
$scope.names = [];
http_factory.get_request().then(function(response){
$scope.names = response.data;
});
});
I have another file called services.js which has a service factory to get details from a json file using an http get.
My only problem seems to be in the above main.js which gives the error below everytime index.html loads
angular.js:88 Uncaught Error: [$injector:modulerr]
Your config is wrong. You pass in a string as the first (and second argument), while the .config(..) function, expects a function to be passed in (or an array).
In your code, you simply forgot to wrap the arguments in an array. Here's how it should look:
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
templateUrl:"update.html",
controller: "update_controller"
})
.when("/view",
{
templateUrl: "view.html",
controller: "view_controller"
});
}]);
Note the [ and ] wrapping the content
You can check with below code.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<body ng-app="new_pr_app">
<h2>Please select an option</h2><br>
<div ng-controller="view_controller">
<button id="view_details" ng-click="view()">View Details</button>
</div>
<div ng-controller="update_controller">
<button id="update_details" ng-click="update_details()">Update Details</button>
</div>
<div ng-view>
</div>
<script>
var app = angular.module('new_pr_app', ['ngRoute']);
app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
template:"update template"
// controller: "update_controller"
})
.when("/view",
{
template: "view template"
// controller: "view_controller"
});
}]);
app.controller("view_controller",function($scope, $location){
$scope.view = function(){
$location.path("/view");
}
});
app.controller("update_controller",function($scope, $location){
$scope.update_details = function(){
$location.path("/update");
}
});
</script>
</body>
</html>

Angular/Ionic Views - where to put controller?

I have an Ionic app that has two views:
Home
Activity
The 'Home' view shows static info with a login screen that takes users to the 'Activity' page where they can see updated info from a $http request to my REST. I can make the call work on a single page, but I dont know where to put the controller when its being used on a view other than the main view and Im unsure how to handle the duplicate specification of the ng-app; its being called in both the 'home' view and the 'activity' view.
Here is my 'Home'
<!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">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/routes.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>
<!-- Only required for Tab projects w/ pages in multiple tabs
<script src="lib/ionicuirouter/ionicUIRouter.js"></script>
-->
</head>
<body ng-app="app" animation="slide-left-right-ios7">
<div>
<div>
<ion-nav-bar class="bar-stable">
<ion-nav-back-button class="button-icon icon ion-ios-arrow-back">Back</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</div>
</div>
</body>
</html>
and here is my 'Activity' view:
<ion-view title="Activity">
<ion-content overflow-scroll="true" padding="true" class="has-header">
<div ng-app="app" ng-controller="users">
<div style="width:100%; text-align:center;">
<table class="pure-table">
<thead>
<tr><td>Device ID</td><td>First Name</td><td>Last Name</td><td>Activity</td></tr>
</thead>
<tbody>
<tr ng-repeat="x in names">
<td>{{ x.Regid }}</td><td>{{ x.Fname }}</td><td>{{ x.Lname }}</td><td>{{ x.activity }}</td>
</tr>
<tbody>
</tbody></tbody></table></div>
<button class="button button-full button-light" id="refresh">
Refresh
</button>
</div>
<div class="bar bar-footer bar-stable">
<div class="title"></div>
</div>
<script>
var app = angular.module('app', []);
app.controller('users', function($scope, $http, $interval) {
$http.get("call to REST.php")
.then(function (response) {$scope.names = response.data.records;});
$interval(MyCtrl, 3000);
});
function callAtInterval(){
//console.log("Interval Occured");
//window.location.reload();
//$state.reload();
}
function MyCtrl($scope )
{
$scope.updateFromModel = 'Initial Value';
setTimeout( function()
{
console.log( 'automatically update view?' );
$scope.updateFromModel = "It's been updated";
$scope.$apply();
}, 1000 );
}
$('#refresh').click(function() {
location.reload();
});
</script>
</ion-content>
</ion-view>
and here are my routes:
angular.module('app.routes', [])
.config(function($stateProvider, $urlRouterProvider) {
.state('login', {
url: '/home',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
.state('activity', {
url: '/activity',
templateUrl: 'templates/activity.html',
controller: 'activityCtrl'
})
$urlRouterProvider.otherwise('/home')
});
You can add controllers in controller.js file same like following code:
app.controller('MyController1', function($scope) {
//write controller specific code here...
});
app.controller('MyController2', function($scope) {
//write controller specific code here...
});
... so on
Or you can define in <script> tag too right after define your app module:
var app = angular.module('app', []);
app.controller('MyController1', function($scope) {
//write controller specific code here...
});
app.controller('MyController2', function($scope) {
//write controller specific code here...
});
... so on
I just figured it out. The controller goes in the controller.js under the controller thats already been established for the activity route.
You have to create a controller for each view/session in a isolated js file (controllers.js) and then declare as a angular module of your app.
Check out the official Ionic Framework Tutorial recommendations
https://ccoenraets.github.io/ionic-tutorial/create-angular-controller.html
angular.module('starter.controllers', [])
.controller('loginCtrl', function ($scope) {
$scope.LoginForm = {};
$scope.Login = function() {
alert($scope.LoginForm.User);
alert($scope.LoginForm.Password);
location.href = "#tab/qr-reader";
};
})
more controllers
...

Blank screen ionic

When running my code I get a blank screen with console error:
GET http://localhost/templates/home.html 404 (Not Found)
resulting in a blank screen.
The code is run into a lamp server (localhost).
My 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>
Inside my app.js config:
.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.otherwise('/tester');
})
TesmenuController:
.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();
});
})
My whole 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.otherwise('/tester');
})
.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
//});
})
OK lets see
this is how your html should look like
<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>
here the Angular part
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 }
];
});
and here a working example http://jsbin.com/diliru/1/edit?html,js,output
remember to do ionic serve in your terminal, be aware of this: <ion-nav-view name="menuContent"></ion-nav-view> should be the same name that you should put here
.state('home.tester', {
url: "/tester",
views: {
'menuContent': {
templateUrl: "templates/tester.html",
controller: 'TesterCtrl'
}
}
});
remember to mention you dependencies.
I don't know what else. Just let me know If I could help.
Ionic has its own server to test your application. AFIK, it's not designed to run on as a normal web site/server. Running as a server is just a tool that they give to build the app more rapidly
So to run the app,
cd to your app folder
run ionic serve
it should start at localhost:8100 by default
read more on their getting started
Can you check which version of Cordova you are using.
cordova -v
if the version is >4.3, try adding the whitelist plugin
ionic plugin add cordova-plugin-whitelist
The new cordova blocks the http request and this error shows up when the application is trying to make http requests.
<access origin="*" />
add the access origin to your config.xml file.
This should solve your problem

Resources