I know this question has been asked many times and after going through the replies and making the changes in my code I am still not able to open a different page by pressing a button. I just started with Angular JS, so can anyone please help me with the same ?
(The address in the url changes but the page is not displayed)
CODE:
Index.html
<!doctype html>
<html ng-app="testAngularApp" class="no-js">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Add your site or application content here -->
<div ng-controller="MainCtrl">
<button ng-click="testButton()"> Page Change</button>
</div>
<script src="bower_components/angular/angular.js"></script>
<!-- endbower -->
<!-- endbuild -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
</body>
</html>
app.js
'use strict';
/**
*
* Main module of the application.
*/
angular
.module('testAngularApp', [])
.config(function($locationProvider){
$locationProvider.html5Mode(true);
});
main.js
'use strict';
/**
* #ngdoc function
* #name testAngularApp.controller:MainCtrl
* #description
* # MainCtrl
* Controller of the testAngularApp
*/
angular.module('testAngularApp')
.controller('MainCtrl', function ($timeout, $log, $location, $scope) {
$scope.testButton = function(){
// Testing the opening of different page.
$log.info($location.path());
$timeout(function () {
$location.path('/views/Dummy.html');
});
};
});
Thanks and Regards,
(The address in the url changes but the page is not displayed)
$location does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
$window.location.href = '/views/Dummy.html';
Your $timeout has no value for how long it should delay. You need to provide it after the function.
$timeout(function () {
$location.path('/views/Dummy.html');
}, 1);
Please inject ngRoute to your app and don't forged add and reference to script angular-route.js
angular
.module('testAngularApp', ['ngRoute'])
.config(function($locationProvider){
$locationProvider.html5Mode(true);
});
and in you controller
$location.path('/path'); <- path has to be defined in your app.config ...(ie .when(/path..)not just path to html file
Related
I have a page that uses angular ui-router to render two views on the same page.
I ultimately need to have this run under phonegap/cordova so will have to bootstrap angular to the elements on a deviceready event.
I managed to encapsulate the code into a function and when the function is called at the end of the page it works fine.
However when the same function is called on the window.onload or document ready event it fails to work. In fact if the function is called from the javascript console itself after page load it just fails to work.
Need help figuring out what is exactly going wrong.
Code below
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.min.js"></script>
<script>
</script>
</head>
<body>
<div ui-view="appview"> appview </div>
<div ui-view="msgview"> messageview s</div>
<script>
var routerApp;
var appViews = ['appview','msgview'];
function zero()
{
routerApp= angular.module('routerApp', ['ui.router']);
x=$("body").attr("ng-app","routerApp");
for(var i=0;i<appViews.length;i++)
{
angular.bootstrap($("#" + appViews[i]), ["routerApp"]);
}
routerApp.config(function($stateProvider, $urlRouterProvider)
{
$urlRouterProvider.otherwise('/messaging');
$stateProvider
.state('messaging',
{
url: '/messaging',
views:
{
'':{templateUrl:'http://geo.tikoo.com/app/components/messaging/phone/messaging.html'},
'msgview':
{
templateUrl: 'http://geo.tikoo.com/app/components/messaging/phone/messaging.html',
controller: 'messC'
}
}
});
});
routerApp.controller('messC', function($scope) {
$scope.username = 'Tom';
});
}
zero();
//window.onload=zero;
//$(document).ready(function(){zero();});
</script>
</body>
</html>
Figured it out after a few attempts.
Here is what needed to be done.
1. The routers need to be set first.
2. The attribute for ng-app on the element needs to be set next.
3. a angular.element(element).ready event needs to be caught to bootstrap
Understanding.
If the routers are not setup first then the bootstrapping fails (obvious)
The ng-app dynamic addition also needs the router setup (Interestingly chrome can work in any order but mobile browser/opera needs that router be setup first before the attribute ng-app is assigned to an element).
SET ROUTERS ==> ADD ng-app Attribute to element ==> Bootstrap
Hope this helps
I have a standard angular page that is not associated with any ui.router functionality(index.html). From that page I click a link that triggers an angular call and than after some operation the flow needs to be redirected to a page inside a folder that is using angular-ui.route template.
I have created a plunker that represents this:
http://plnkr.co/edit/7UQTlMRQBMXGaRdHlPfs?p=preview (current plunker is working but there's a loop on first page trying to call default state created with $urlRouterProvider.otherwise('events');)
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.3.16" data-semver="1.3.16" src="https://code.angularjs.org/1.3.16/angular.js"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="LoginController as lgCtrl">
<h1>This page does not use ui.router</h1>
Login
</body>
</html>
The page with ui-view tag is inside a manage folder:
manage/home.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.angularjs.org/1.3.16/angular.js" data-semver="1.3.16" data-require="angular.js#1.3.16"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
<script type="text/javascript" src="../app.js"></script>
</head>
<body ng-controller="EventsController as evtCtlr">
<h1>Hello manage/home.html</h1>
<div ui-view></div>
</body>
</html>
The templateUrl page to be inserted is:
manage/events.html
<div ng-controller="EventsController as evtCtrl">
<h3>Events Page</h3>
<div>Some user email</div>
</div>
app.js
'use strict';
(function () {
var app = angular.module('app', ['ui.router']);
/**
* Configuration for ui-router module. Handles navigation based on app states.
*/
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('events');
$stateProvider
.state('events', {
url: '/events',
views:{
'#manage/home':{
templateUrl: 'manage/events.html'
}
}
});
});
app.controller('LoginController', ['$scope','$window', '$state',
function($scope, $window, $state){
$scope.goToEvents = function(){
console.log('trying to load events');
//this call doesn't work, 404 - It should?? -->> see reference
//https://github.com/angular-ui/ui-router/wiki/URL-Routing
$window.location.href = 'manage/home.html/events';
//don't work
//$state.transitionTo('events');
//also don't work
//$state.go('events');
};
}]);
app.controller('EventsController', [function(){
console.log('EventsController');
}]);
})();
I have created a plunker that represents this:
http://plnkr.co/edit/7UQTlMRQBMXGaRdHlPfs?p=preview
I have tried different ways of moving from the first non ui.router page but none worked so far.
What's the best way of doing this?
Firstly , do not inject $state as dependency in the LoginController as the view related to this controller isn't an UI route. Adding the $state dependency causes the loop that you are seeing in your example as UI-Router then considers this view a route. As no state matches this route , it tries to load the default state , whose template has a relative URL , which then looks it up inside wrong directory of Plunkr , which causes 404 error.
Secondly , the URL to redirect should via location.href should have a hash otherwise it will also give 404
The code for the LoginController
app.controller('LoginController', ['$scope', '$window',
function($scope, $window) {
$scope.goToEvents = function() {
//Do Something
$window.location.href = 'manage/home.html#/events';
};
}
]);
Check the working example at http://plnkr.co/edit/K2iBYu?p=preview
I want to be able to quickly build an AngularJS application using ui-router without having to set up a server. So that I can send this folder to anyone and the application will still work.
I have tried putting a # infront of the route as adviced here. I have also tried to follow other advice related to the ngroute, but nothing seems to work and since I want to use ui-router rather than ng-route I'm not sure whether the advice is even applicable to my situation.
I have also tried to create a manifest file to store the files offline according to this page.
In firefox it kind of works but for some reason it double up what is on the index.html page. But in chrome which is my preferred browser it doesn't work at all. I get an error about a failed ajax call; why don't the manifest file download all pages straight away?
How should I accomplish building an AngularJS app with ui-router without needing a server?
Here is simple snippet of my code:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="app" manifest="mycache.manifest">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<a ui-sref="home.messages">Messages</a>
<div ui-view></div>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="js/routes.js"></script>
<script src="js/main.js"></script>
</body>
</html>
messages.html
<button ng-click="contextCtrl.getAllMessages()">Get Messages</button>
<div ng-repeat="message in contextCtrl.messages">
{{message}}
</div>
routes.js
'use strict';
angular.module('app', ['ui.router']);
//Setting up route
angular.module('app').config(['$stateProvider',
function($stateProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'index.html',
controller: 'ContextCtrl',
controllerAs:'contextCtrl'
})
.state('home.messages', {
url: '/messages',
templateUrl: 'messages.html',
controller: 'ContextCtrl',
controllerAs:'contextCtrl'
});
}
]);
main.js
'use strict';
/*jslint latedef:false*/
//Controller declaration
angular.module('app').controller('ContextCtrl', ContextCtrl);
function ContextCtrl() {
var vm = this;
vm.messages = [];
vm.getAllMessages = getAllMessages;
function getAllMessages(){
vm.messages = ['m1', 'm2', 'm3', 'm4'];
};
}
mycache.manifest
CACHE MANIFEST
js/main.js
js/routes.js
messages.html
bower_components/angular-ui-router/release/angular-ui-router.js
bower_components/angular/angular.js
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...
I have a problem with boostrapping an angularjs app - with initialization code in the controller. The simplified test-case is like this (index.js):
var myApp = angular.module( 'myApp', []);
myApp.controller( 'myAppController', [ '$scope', function($scope) {
console.log('never shown');
$scope.test = 'constructor called';
// removed more init code
}]);
$(document).ready(function(){
angular.bootstrap( document, ['myApp']);
console.log('Finished boostrapping.');
});
The HTML file for this test-case:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TeST</title>
</head>
<body>
{{test}}
<script type="text/javascript" src="js/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="js/bower_components/angular/angular.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
The result is that console output only says "Finished bootstrapping" - and the controller function is never invoked. .. This baffles me a little, but this is my first angular 1.2 app. I get the same result If I put ng-app="myApp" in the tag and let angular bootstrap the app automatically. ...
you never set ng-controller anywhere in your markup.
also, you should either put your script tags in the head, or after </body>.
edit: when using bootstrap this way, the placement of the <script> tags goes matter.
The first parameter to the angular.bootstrap method is an element. Currently you are passing in document, which is not an element.
Try
angular.bootstrap(document.documentElement, ['myApp']);
or
angular.bootstrap(document.body, ['myApp']);