Blank screen ionic - angularjs

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

Related

Not able to inject resolved object from ui-route change into the controller

I am trying to access an http get response called during route change using ui route. The resolve itself happens but i am unable to access the response. I have tried some approaches in "listcontroller" which is shown. I am using a sample httpget url found in the internet for test. Angular version: v1.2.32. ui-route: 1.0.15.
script.js
var app = angular.module("Rasp", ["ui.router"])
.config(['$stateProvider', '$urlRouterProvider',function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state("ipList", {
url: "/ipList",
templateUrl: "templates/list.html",
controller: "listController",
resolve: {
SensorIP : function($http){
$http.get('https://httpbin.org/ip')
.then(function(response){
console.log('res');
console.log(response);
return response.data.origin;
});
}
}
})
.state("home", {
url: "/home",
templateUrl: "templates/home.html",
controller: "homeController"
});
}])
.controller("RaspController", ['$scope', '$http', function ($scope, $http) {
$scope.getDetails = function () {
// $http.get('https://httpbin.org/ip')
// .then(function (response) {
// console.log(response);
// $scope.response = response;
// },
// function (error) { console.log(error); }
// );
// };
}])
.controller("homeController", ['$scope', function ($scope) {
}])
.controller("listController", ['$scope','SensorIP',function ($scope,SensorIP) {
$scope.sensorList = SensorIP;
var vm = this;
this.list1 = SensorIP;
var logfunc = function() {console.log($scope.sensorlist)};
}])
list.html
<div>
{{list1}}
{{sensorlist}}
<button class="btn btn-danger navbar-btn" ng-click="logfunc()">click</button>
</div>
home.html
<h4>Click on "Get IP List" to get the list of IPs</h4>
<a ui-sref="ipList"><button id="button" >Get IP List</button></a>
index.html
<!DOCTYPE html>
<head>
<title>Title(To be changed)</title>
<!--JS-->
<script type="text/javascript" src="../node_modules/angular/angular.js"></script>
<script type="text/javascript" src="../node_modules/#uirouter/angularjs/release/angular-ui-router.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- -->
<!--CSS-->
<link rel="stylesheet" href="../css/style.css">
<!-- -->
</head>
<body>
<div ng-app="Rasp">
<div ng-controller="RaspController">
<div class="sidenav">
<!--
<a ui-sref="home" id="dot-button"><button class="btn btn-danger navbar-btn" >Home</button></a>
<a ui-sref="ipList" id="dot-button"><button class="btn btn-danger navbar-btn" >IP List</button></a>
-->
<a ui-sref="home">home</a>
<a ui-sref="ipList" >ipList</a>
</div>
<div>
<ui-view id="uiview"></ui-view>
</div>
</div>
</div>
</body>

change page title in ui-router not work

i try to change my page title in angular app use ui router
i found this demo and its work fine https://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview
but when i attempt to try the same demo not work i need to find issue that make my demo not work https://plnkr.co/edit/pqumJL?p=preview
why demo not change page title although it's work in demo
try this :
(function () {
'use strict';
angular
.module('app', ['ui.router'])
.config(config)
config.$inject = ['$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider'];
function config($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) {
$urlRouterProvider.otherwise('/home');
$urlMatcherFactoryProvider.caseInsensitive(true);
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.view.html',
data: {
pageTitle: 'Home'
}
})
.state('about', {
url: '/about',
templateUrl: 'about.view.html',
data: {
pageTitle: 'About'
}
})
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<script src="https://code.angularjs.org/1.3.3/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.min.js"></script>
<script src="app.js"></script>
<script src="app-directives/title-directive.js"></script>
<title>{{title}}</title>
</head>
<body>
<div class="panel" ui-view></div>
<ul class="nav navbar-nav">
<li>
<a ui-sref="home" ui-sref-active="activeState">Home</a>
</li>
<li>
<a ui-sref="about">About</a>
</li>
</ul>
</body>
</html>
https://plnkr.co/edit/JifcOKrUC9tBfV8jY5ko?p=preview
In plunkr you just have to replace
<script src="app-directives/title-directive.js"></script>
by
<script src="title-directive.js"></script>
I can provide you a better way to do so:
link: function (scope, element, attrs) {
var defaultTitle = element.text();
if (element[0].tagName === 'TITLE') {
var listener = function (event, toState) {
var title;
if (toState.data && toState.data.pageTitle) {
if(toState.data.placeholder && toState.data.placeholder.title)
title = toState.data.pageTitle, toState.data.placeholder.title;
else
title = toState.data.pageTitle;
} else if (defaultTitle) {
title = defaultTitle;
} else {
title = 'No title';
}
$timeout(function () {
element.text(title);
}, 0, false);
};
$rootScope.$on('$stateChangeSuccess', listener);
}
}
Thanks the problem solved
there is an error in ui router script and incompatible version
when use online version the problem solved
thanks all

google map application passing latitude and longitude so that the user can then navigate to the place

I am a new to Ionic. I have done some google search but I am still a bit confused.
From my android Ionic app I would like to launch the google map application passing latitude and longitude so that the user can then navigate to the place.
Is is possible? Any help is very appreciated.
Thanks in advance,
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">
<!-- 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="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.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>
</head>
<body ng-app="starter" ng-controller="main">
<div ui-view>
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Login App</h1>
</ion-header-bar>
<ion-content>
<div>
</div>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="postLogin()">Login</button>
</ion-content>
</ion-pane>
</div>
</body>
</html>
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'
var app = angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
}).config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'index.html',
controller: 'main'
})
.state('userPositionInMap', {
url: '/userPositionInMap',
templateUrl: 'map.html',
controller: 'MapController'
})
$urlRouterProvider.otherwise('/login');
});
app.controller('main', function ($scope,$http,$stateParams,$ionicPopup,$location)
{
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password,
latitude,
langitude
};
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
data.latitude=response.latitude;
data.langitude=response.langitude;
$location.path("/userPositionInMap");
},
function(response){
// failure callback
console.log('error');
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
}
);
}
});
app.controller('MapController', function ($scope,$stateParams)
{
});
map.html
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsiDiIzQjg7U9JYPDVl8hnfZ7MwDcHDHg&signed_in=true&libraries=places&callback=initMap" async defer></script>
<script>
function initMap() {
var position = new google.maps.LatLng({lat: 48.85661400000001 , lng: 2.3522220000000177 });
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.85661400000001 , lng: 2.3522220000000177 },
zoom: 15
});
var marker = new google.maps.Marker({
position: position,
map: map,
title: ""
});
//var input = document.getElementById('address');
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(myLatlng);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
//anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function () {
marker.setVisible(false);
var place = autocomplete.getPlace();
if (place != undefined) {
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
console.log(place.geometry.location.toString());
$('#lat').val(lat);
$('#lng').val(lng);
}
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}
</script>
<ion-view view-title="Map">
<ion-content class="padding">
<div class="list card">
<div class="item item-divider">Map</div>
<div class="item item-body">
<div id="map" style="width:100%; height:100%;"></div>
</div>
</div>
</ion-content>
</ion-view>
I have a rough idea of what you are tying to achieve. You can wrap your code for the map in a directive, then via the link function you can access $rootScope which you can use to hold the lat and lng from the database. Here is the doc for directives: https://docs.angularjs.org/guide/directive
Try to use Angular-maps : https://angular-maps.com/
#Component({
selector: 'app-root',
styles: [`
agm-map {
height: 300px;
}
`],
template: `
<agm-map [latitude]="lat" [longitude]="lng"></agm-map>
`
})
export class AppComponent {
lat: number = 51.678418;
lng: number = 7.809007;
}

Ionic Controller and Service Structure

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.

AngluarJS Facebook buttons do not show up on the first time I load the page

I'm able to my buttons work. The only is that I can't get them to work with AngluarJS. This is what happens: When I click the link to enter the page to where my facebook buttons are located, they don't show the first time. They only show up every time I click the refresh button at the top. How can I make it work so that they always show up right when I click the link to the page? My facebook div content code is under third.html which I labeled as FB Test on the app website. My script code for facebook is on my index.html page which is also where I set up my angular to link and label each page. Plus, please use a local host to test the app website. Here's my code:
index.html has...
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/master.css">
<script src= "js/angular.min.js"></script>
<script src= "js/angular-route.min.js"></script>
<script src= "js/jquery-2.1.3.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<link href="js/angular.min.js.map"></link>
<link href="js/angular-route.min.js.map"></link>
<script>
var pattern = /http:.+?(?=.jpg)(....)/;
var pieces = [];
var data = $.ajax({
dataType: "json",
url: "js/data.json",
success: function(){
$.each(data.responseJSON,function(){
//todo: add a placeholder image if there wasnt a url
if(this.piece_image != ""){
this.image_URL = /http:.+?(?=.jpg)(....)/.exec(this.piece_image)[0];
}
pieces.push(this);
})
data.destroy;
}
});
</script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<!--style effects comment box position-->
<style>
.fb-comments, .fb-comments iframe[style], .fb-like-box, .fb-like-box iframe[style] {
width: 100% !important;
}
.fb-comments span, .fb-comments iframe span[style], .fb-like-box span, .fb-like-box iframe span[style] {
width: 100% !important;
}
</style>
</head>
<body ng-app="app" style="padding-top:20px;">
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
//*This is where our app id must go
//Note to myself:
//the following number was created from my test app called "Davidow Project test" which is currently not live
//login to facebook, go to https://developers.facebook.com/apps/ to see test app
appId : '435225213325487',
channelUrl : '//localhost:8080/#/second',
status : true,
xfbml : true,
version : 'v2.1'
});
};
</script>
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}
(document, 'script', 'facebook-jssdk'));
</script>
<div class="container">
Home |
Explore |
Gallery |
Map |
Tile View |
FB Test
<div ng-view></div>
<!--TWITTER-->
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
</body>
</html>
**third.html has...**
<!--FACEBOOK CONTENT-->
<!--*must replace data-href with url of app site-->
<!--like button and share buttons-->
<div class="fb-like" data-href="http://www.example.com/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<!--comment section-->
<!--added in a data-width number to resize comment box-->
<div class="fb-comments" data-href="http://www.example.com/" data-numposts="3" data-width="350px;" data-colorscheme="light"
data-layout="standard"></div>
<!--TWITTER-->
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
Tweet
**app.js has...**
var app = angular.module("app", ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: './views/main.html',
controller: 'mainController'
})
.when('/explore', {
templateUrl: './views/explore.html',
controller: 'mainController'
})
.when('/gallery', {
templateUrl: './views/gallery.html',
controller: 'gallery'
})
.when('/map', {
templateUrl: './views/map.html',
controller: 'mainController'
})
.when('/tileView', {
templateUrl: './views/tileView.html',
controller: 'tileView'
})
.when('/fbtest', {
templateUrl: './views/third.html',
controller: 'mainController'
})
});
app.controller('mainController', ['$scope', '$location', '$log', function($scope, $location, $log){
}]);
app.controller('gallery', ['$scope', '$location', '$log', function($scope, $location, $log){
$scope.pieces = pieces;
}]);
app.controller('tileView', ['$scope', '$location', '$log', function($scope, $location, $log){
window.scope = $scope;
$scope.pieces = pieces;
$scope.url = [];
for(var i = 0; i < pieces.length; i++){
$scope.url.push(pieces[i].image_URL);
}
}]);
You are loading the Social Plugins asynchronously, so you need to use FB.XFMBL.parse after loading them:
FB.XFBML.parse();
Source: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse

Resources