Ionic structure same as Angularjs - angularjs

I know a little bit about Angularjs (I'm still learning) and now I want to learn Ionic too. I tried to have same structure approach for code organization, but it seems that I don't know how to make same code works on Ionic. Can someone helps me, I will write my code first and then explain what is the problem.
index
<!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">
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="app/application.js"></script>
<script src="app/controllers/userDataCtr.js"></script>
</body>
</html>
app
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
controller: 'userDataCtr',
templateUrl: 'app/views/home.html'
})
;
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/home');
});
controller
(function() {
'use strict';
angular
.module('starter')
.controller('userDataCtr', userDataCtr);
userDataCtr.$inject=['$state','$window'];
function userDataCtr($state,$window) {
var vm = this;
vm.test = test;
function test() {
vm.testing = "Does work?";
}
}
})();
home view
<div ng-init="userDataCtr.test()">{{testing}}</div>
When I start application I get nothing on screen, blank page. It seems like function is not even started. Does anyone know where I'm wrong?
Thanks
Edit:
Now I figure out that if I change this:
(function() {
'use strict';
angular
.module('starter')
.controller('userDataCtr', userDataCtr);
userDataCtr.$inject=['$state','$window'];
function userDataCtr($state,$window) {
var vm = this;
vm.test = test;
function test() {
vm.testing = "Does work?";
}
}
})();
to this:
(function() {
'use strict';
angular
.module('starter')
.controller('userDataCtr', userDataCtr);
userDataCtr.$inject=['$state','$window','$scope'];
function userDataCtr($state,$window,$scope) {
$scope.test - function() {
$scope.testing = "Does work?";
}
}
})();
Works !!
But I don't want to use $scope. Does anyone knows why first solution fail and another works?

Related

AngularJS controller not accessed

I am learning AngularJS and I have a problem with the controller.
This example below already worked, but it suddenly stoped without any changes that could cause that. I am not sure what is wrong.
The /templates/index.html file does not load.
This is my main index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Todolist</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- ANGULAR JS -->
<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-ui-router/1.0.3/angular-ui-router.min.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/todolists.js"></script>
</head>
<body ng-app="app">
<div ui-view></div>
</body>
</html>
This is my app.js:
var app = angular.module('app', ['ui.router']);
app.config(function ($stateProvider) {
$stateProvider
.state('/', {
url: "/",
templateUrl: "app/templates/index.html",
controller: 'todolists',
});
});
This is my todolists controller:
var app = angular.module('app');
var controllers = {};
console.log("test");
controllers.todolists = function ($scope, $http) {
console.log("test1");
$http.get('http://localhost:8888/todolist/rest/entries/index.json').
then(function(response) {
console.log(response.data);
$scope.data = response.data;
});
};
app.controller(controllers);
console.log("test") writes to console, but console.log("test1") does not, so the controller is not accessed.
Please take a look and let me know if you have and tips about what could be wrong.
Thanks, Grega
You need to register a name for the controller is the problem. Ive registered the name 'todolistCtrl' which is the first argument needed for the controller registration method. the second argument is the function controllers.todolists.
you can then reference todolistCtrl within you State Provider.
controller
var controllers = {};
console.log("test");
controllers.todolists = function ($scope, $http) {
$http.get('http://localhost:8888/todolist/rest/entries/index.json').
then(function(response) {
console.log(response.data);
$scope.data = response.data;
});
};
angular.module('app')
.controller('todolistCtrl', controllers.todolists);
app
var app = angular.module('app', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: "/",
templateUrl: "index.html",
controller: 'todolistCtrl',
});
});
Plunker
Example

Having problems injecting dependencies in angularjs

I am a newbie in angularjs. My intention is to add this angularjs directive https://github.com/720kb/angular-datepicker to my app.js so that I can be able to select dates in one of my views buses.html.
My app.js file looks something like this:
My app.js file looks like this...
var busRest1 = angular.module("busReservator1", ["720kb.datepicker"]);
//dependency injection that fails
var busRest = angular.module("busReservator", ["ionic", "busRest1"]);
busRest.run(function($ionicPlatform, $state) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
document.addEventListener("resume", function() {
$state.go("home", {}, {location: "replace"});
}, false);
});
busRest.factory('myService', function(){
var savedData = {}
function set(data){
savedData = data;
}
function get(){
return savedData;
}
return {
set: set,
get: get
}
});
busRest.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state("home", {
url: "/home",
templateUrl: "templates/home.html",
controller: "homeCtrl",
})
.state("busList", {
url: "/busList",
templateUrl: "templates/busList.html",
controller: "busListCtrl",
cache: false
})
$urlRouterProvider.otherwise('/home');
});
busRest.controller("homeCtrl", ['$scope', function($scope){
}]);
busRest.controller('busListCtrl', ['$scope', 'myService2', function($scope, myService2) {
//declaring an array of transporters
$scope.transporters = [];
$scope.AddTransporter = function(){
transporters = [document.getElementById('transporter_agency').value, document.getElementById('transporter_vehicleType').value, document.getElementById('transporter_vehicleCapacity').value, document.getElementById('transporter_btnValue').value];
myService2.set(transporters);
};
}]);
busRest.controller('DataCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('js/datafile2.json').success(function (data) {
$scope.artists = data.artists;
$scope.albums = data.albums;
})
}]);
My index.html looks like this
<!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>Bus Ticket Reservation</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- For the date picker css-->
<link href="src/css/angular-datepicker.css" rel="stylesheet" type="text/css" />
<!-- For the date picker js -->
<script src="src/js/angular-datepicker.js"></script>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/forge.min.js"></script>
<script src="js/firebase.js"></script>
<script src="js/angularfire.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="busReservator">
<ion-pane>
<ion-nav-bar class="bar-royal"></ion-nav-bar>
<ion-nav-view ></ion-nav-view>
</ion-pane>
</body>
</html>
When I save and run, the app breaks and the browser window is emptied

$destroy event not being called on navigation

I have registered for hardware back button event registerBackButtonAction inside my controller and using $destroy event to unregister the event. But the event is not getting called when I navigate to different page (state). What am I missing?
.controller('HomeCtrl', function($scope, $ionicPlatform, $location, $rootScope, $http) {
// Register hardware back button
var deregister = $ionicPlatform.registerBackButtonAction(function (event) {
navigator.app.exitApp();
return;
}, 100);
console.log('scope on');
$scope.$on('$destroy', function() {
console.log('destroy called');
deregister();
})
})
In console I dont see destroy called. Please help me fix this.
Update:
In the browser when I navigate from Home to Login the elements of Home still exist in the browser. I guess that is the reason why destroy is not getting called. So the question is should I fire the event manually or should be Home page be actually destroyed when I move to Login?
Here is 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="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
<link href="css/ionic.app.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- Push notification -->
<script src="js/PushNotification.js"></script>
<!-- Geo location -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<!-- app js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="starter" ng-controller="AppCtrl">
<ion-nav-view></ion-nav-view>
</body>
</html>
The page are loaded as part of state via template in app.js:
.state('app.login', {
url: "/login",
views: {
'menuContent': {
templateUrl: "templates/login.html",
controller: 'LoginCtrl'
}
}
})
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "templates/home.html",
controller: 'HomeCtrl'
}
}
})
Thanks for the help guys. In my framework the elements of first loaded page are not removed hence $destroy is not called. The workaround is to use the event $ionicView.leave to deregister, so instead of
$scope.$on('$destroy', deregister);
use:
$scope.$on('$ionicView.leave', deregister);
Complete code:
.controller('HomeCtrl', function($scope, $ionicPlatform, $location, $rootScope, $http) {
// Register hardware back button
var deregister = $ionicPlatform.registerBackButtonAction(function (event) {
navigator.app.exitApp();
return;
}, 100);
$scope.$on('$ionicView.leave', deregister);
})
I was supposed to wrap deregister() in an anonymous function. Then it worked for me.
var deregister = $ionicPlatform.registerBackButtonAction(function () {
$state.go('app.start');
}, 100);
$scope.$on('$ionicView.leave', function () {
deregister();
});
This Work for me
var deregister = null;
$scope.$on('$ionicView.enter', function(){
deregister = $ionicPlatform.registerBackButtonAction(
function () {
navigator.Backbutton.goHome(function() {
console.log('hidden');
}, function() {
navigator.app.exitaApp();
});
}, 100
);
})
$scope.$on('$ionicView.leave', function () {
deregister();
});

ngRoute not working

My scripts are :
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>My Application</title>
</head>
<body>
<div ng-view></div>
<script src="/assets/vendor/angular/angular-1.2.16.min.js"></script>
<script src="/assets/vendor/angular/extras/angular-route.js"></script>
<script src="/assets/myapp/myApp.js"></script>
</body>
</html>
myApp.js
(function () {
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
template: '<h1>Home</h1>',
controller: function () {
console.log('Home');
}
}).
when('/books', {
template: '<h1>Books</h1>',
controller: function () {
console.log('Books');
}
});
$locationProvider.html5Mode(true);
console.log('routes configured');
}]);
})();
I've wasted a lot of time trying to figure out what the problem might be with no luck. Am I missing something silly? thanks in advance for the help.
Are you hosting your application in the root of your server? If not, then you will need to use the tag below in your head tag.
<base href="PATH_HERE" />
In addition, can you comment out the $locationProvider.html5Mode(true) line and get your app working in hash routing mode first?
Just a question, but it is possible to add a function in the controller -> controller:function()? Because normally i would do it like this. controller:'mainController' and put the function in the mainController.

Cant integrate facebook login to angular app using ngFacebook

Somehow I am not able to integrate facebook Login to my angularjs app, though I feel I am just loosing a minor mistake which I cant point out and thus you geeks might be sureshot help!
I have used this plunker example:
Following the above code same as what has been mentioned in plunker, below are y files.
my app.js {which has nothing but routing info, ngFacebook module I have injected in controller.js}
'use strict';
// Declare app level module which depends on filters, and services
angular.module('ngdemo', ['ngdemo.filters', '$strap.directives', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view5', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl4'});
$routeProvider.when('/view1', {templateUrl: 'modulepages/home.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.when('/view4', {templateUrl: 'modulepages/bizregistration.html', controller: 'MyCtrl3'});
$routeProvider.when('/view6', {templateUrl: 'partials/modalcontent.html', controller: 'MyCtrl5'});
$routeProvider.otherwise({redirectTo: '/view5'});
}]);
And this is my Controller.js which has the heart of ngFacebook Integration.
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', ['ngResource', 'ngFacebook'])
.config([ '$facebookProvider', function( $facebookProvider ) {
alert("am i here?");
$facebookProvider.setAppId('239661002870669');
}]);
// Clear browser cache (in development mode)
//
// http://stackoverflow.com/questions/14718826/angularjs-disable-partial-caching-on-dev-machine
app.run(function ($rootScope, $templateCache) {
(function(){
// If we've already installed the SDK, we're done
if (document.getElementById('facebook-jssdk')) {return;}
// Get the first script element, which we'll use to find the parent node
var firstScriptElement = document.getElementsByTagName('script')[0];
// Create a new script element and set its id
var facebookJS = document.createElement('script');
facebookJS.id = 'facebook-jssdk';
// Set the new script's source to the source of the Facebook JS SDK
facebookJS.src = '//connect.facebook.net/en_US/all.js';
// Insert the Facebook JS SDK into the DOM
firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
}());
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('DemoCtrl', ['$scope', '$facebook', function ($scope, $facebook) {
alert("I am here out");
$scope.isLoggedIn = false;
$scope.login = function() {
$facebook.login().then(function() {
refresh();
});
}
function refresh() {
$facebook.api("/me").then(
function(response) {
$scope.welcomeMsg = "Welcome " + response.name;
$scope.isLoggedIn = true;
},
function(err) {
$scope.welcomeMsg = "Please log in";
});
}
refresh();
}]);
and that's my index.html
<!DOCTYPE html>
<html ng-app="ngdemo" lang="en">
<head>
<meta charset="utf-8">
<title>You local needs are just a pingle away - pingle.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="DemoCtrl" bgcolor="#e8e8e8">
<div class="container">
<h4>
{{welcomeMsg}}
</h4>
<button type="button" ng-click="login()" ng-hide="isLoggedIn" class="btn btn-default navbar-btn">
Login
</button>
</div>
<div id="fb-root">
</div>
<div ng-view>
</div>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-strap.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.7.0.js">
</script>
<script src="//rawgithub.com/GoDisco/ngFacebook/master/ngFacebook.js"></script>
</body>
</html>
Could you please help where the problem is, it will be a great help and it is the important part of my application.
I just copied/pasted your code in my IDE and tested it.
I had to remove some things to simplify the testing.
E.g. remove filters, directives, services and also the config for the routeprovider.
I also removed angular-strap. I updated the facebook app id to an ID of an app I own...
If you remove everything you can get it working, then you can gradually add what you need, like routing, angular-strap etc. maybe one of those creates problems...
The code you provided (cleaned with all unnecessary stuff) just worked fine for the facebook login, like the plunker code...
At the moment of writing, if you do not specify the API Facebook version you may get an error in the console, thus I specify it like this:
angular.module('app')
.config(function ($facebookProvider) {
$facebookProvider.setAppId(facebookAppId);
$facebookProvider.setCustomInit({
version: 'v2.1'
});
$facebookProvider.setPermissions('email');
});
Actually I think this question can be closed because the code provided was incomplete and needed some effort, like removing all the unneded stuff as I mentioned...

Resources