in my angularJS app I use symfony as rest API.
Depending on my current url I'm using the $http under app_dev.php or not.
I realized this with the following code:
app.run (function( $rootScope, $location ){
$rootScope.dev = "";
if ( $location.absUrl().search("app_dev.php") > 0 ) {
$rootScope.dev = "app_dev.php/";
}
}
app.controller('OfferIndexCtrl', function($scope, $http, $location, $filter, $rootScope){
$http.get( $rootScope.dev + 'stage/offer/get').success(function(json){
$scope.offerList = json.offerList;
});
}
This works fine. But the .run() runs after .config() and its not possible to integrate it into the routeProvider.
Can anyone help me to integrate this into my routeProvider
app.config(['$routeProvider', '$locationProvider',
function( $routeProvider, $locationProvider ){
$routeProvider.
when('/', {
templateUrl: 'stage/view/offer/index',
controller: 'OfferIndexCtrl'
}).
otherwise({
redirectTo: '/'
})
}
]);
You should use <base> tag to set base URL for your app, and set your base to "/" or "/app_dev.php/" depending on your Symfony environment, using TWIG helpers for environment. You can use this for "app_test.php" as well.
<base href="{{ path('homepage') }}">
With this your whole application will just work on that base URL, you don't need anything more.
How base HTML5 tag works with AngularJS application is described in detail here ngRoute set base url for all routes
If I'm using plain JS befor the Angular part I can use this variable from there.
Following code worked for me:
var dev = "";
if ( location.pathname.search("app_dev.php") > 0 ) {
dev = "app_dev.php/";
console.log( "App läuft unter dev");
}
App.config(['$routeProvider', '$locationProvider',
function( $routeProvider, $locationProvider ){
$routeProvider.
when('/', {
templateUrl: dev + 'stage/view/offer/index',
controller: 'OfferIndexCtrl'
}).
}
Related
I am making an angularjs app but my routing part is not working.
Once I login into application using Login.html,it should route to index.html but it is not working.
app.js
/**
* Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'index.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}]);
I uploaded all my custom files at below location.
http://plnkr.co/edit/mi2JS4y2FfMD9kIl58qk?p=catalogue
I have already included all the dependency files like angular.js and angular-route.js etc..
Thanks in advance.
Here is a working plunker based on your code. You are missing the ng-view that the ngRoute will replace based on your config. So, the index.html looks like:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ng-view></ng-view>
</body>
ng-view is an Angular directive that will include the template of the current route (/main or /home/student) in the main layout file. In plain words, it takes the file based on the route and injects it into the main layout (index.html).
In the config, ng-view will be replace by 'main' that points to Login.html. I change the '/home/student/' to point to a new page 'dic.html' to avoid infinite loop as it used to point to index.html
var app = angular.module('plunker', ['ngRoute', 'Controllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'dic.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}
]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
Like your example, if one logs in with 'harish' as an e-mail and 'harish' as a password, the successCallback is called and goes to '/home/student' that replaces ng-view by dic.html:
$scope.validate = function() {
$http.get('credentials.json').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Data: ' + JSON.stringify(response));
$scope.users = response.data;
var count = 0;
for (var i = 0, len = $scope.users.length; i < len; i++) {
if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
alert("login successful");
count = count + 1;
if ($scope.users[i].role === "student") {
$location.path('/home/student');
break;
}
}
}
if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error: " + JSON.stringify(response));
alert(JSON.stringify(response));
});
};
Let us know if that helps.
You need to add ng-view in the index.html inside the ng-app.
Something like..
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Now, the angular app would assign the view template and controller as defined by your routes configuration, INSIDE the ng-view directive.
Also, should have a generic index.html where all dependencies are included, and render the templates & assign them controllers in accordance with routes configurations. No need to create separate files which includes the dependencies all over again, like you did with index.html and login.html.
You have not injected $location in your controller.
app.controller('MainCtrl', function($scope, $http, $location) {
$scope.name = 'World';
});
I am really new with AngularJS and I have been working in an example for few days
https://github.com/cornflourblue/angular-registration-login-example. The thing is that im trying to read a cookie that i sent from server, and in that example the angular-cookie library is so old like (1.2) so i replaced it with the newest one. The problem comes when im trying to access to the run method, i've no access to $cookies var, i tried to inject it without injecting.
I actually have no idea what's happening. So if you could help me a bit (&& ||) recommend me newest and nicer examples would be awesome.
(function () {
'use strict';
var app = angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'AngularJS/home/home.view.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'AngularJS/login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'AngularJS/register/register.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: 'AngularJS/login' });
}
run.$inject = ['$rootScope', '$location', '$http'];
function run($rootScope, $location, $http, $cookies) {
//I want to use $cookies here, but i canno't seem a possible way.
// keep user logged in after page refresh
$rootScope.globals = $cookies.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})();
Sorry for my poor skills in English... (Not my mothertoungue) :·)
Thanks alot.
You forgot to add $cookies to the run.$inject array.
Moreover, defining .$inject arrays is optional as long as you use the standard dependencies names in your component functions' parameters. Here removing your .$inject definitions should leave you with a lighter and functional application.
I am using AngularJs with Ruby on Rails.
I set the html5 option to true in angular: $locationProvider.html5Mode(true)
But now when I try to navigate through pages in my application, it will only change the URL in my browsers URL bar. But the page it self will nto change unless I reload the page. Only then will it go to the page specified.
This is how my Angular routing looks like:
#test.config(['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
# Route for '/'
$routeProvider.when('/', { templateUrl: '../../views/visitors/index.html.erb', controller: 'VisitorsCtrl' } )
$routeProvider.when('/users', { templateUrl: '../../views/users/index.html.erb', controller: 'UsersCtrl' } )
# Default
$routeProvider.otherwise( { redirectTo: "/" } )
$locationProvider.html5Mode(true)
])
On the root page I have a element: <h2><a ng-click="viewUsers()">Users</a></h2>
And viewUsers() is called here:
#test.controller 'VisitorsCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) ->
$scope.viewUsers = ->
$location.path('/users')
console.log("Redirected")
]
What could be needed more to get this kind of routing to work?
New angular route:
Test.config ($routeProvider, $locationProvider) ->
$routeProvider
.when '/',
templateUrl: '../../views/visitors/index.html.erb',
controller: 'VisitorsCtrl'
.when '/users',
templateUrl: '../../views/users/index.html.erb',
controller: 'UsersCtrl'
try to use following instead:
$window.location.href = '/users'
I'm trying to use Angular.js $routeProvider for my prototype app, it does work fine on my local machine, but fails on production environment. There are nor errors printed on console neither any xhr request sent to get /partials/signup.php template
window.$APP = angular.module('ccnApp', ["ngRoute", "ccnControllers", "ccnServices"]);
window.$SERVICES = angular.module('ccnServices', ['ngResource']);
window.$CONTROLLERS = angular.module("ccnControllers", ["angularFileUpload"]);
/**
* Routes
*/
$APP.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/profile', {
controller: 'ProfileController',
templateUrl: THEME_URL + 'partials/profile.html'
}).when('/profile/:profileId', {
controller: 'ExternalProfileController',
templateUrl: THEME_URL + 'partials/external-profile.html'
}).when('/vault', {
controller: 'VaultController',
templateUrl: THEME_URL + 'partials/vault.html'
}).when('/network', {
controller: 'NetworkController',
templateUrl: THEME_URL + 'partials/network.html'
}).when('/signup', {
controller: 'SignupController',
templateUrl: THEME_URL + 'partials/signup.php'
}).when('/login', {
controller: 'LoginController'
}).when('/payment', {
templateUrl: THEME_URL + 'partials/payment.php'
}).when('/:page', {
templateUrl: function(parameters) {
document.location.href = "/" + parameters.page
}
});
$locationProvider
.html5Mode(true)
.hashPrefix('!');
}]);
Here is the app url http://ccn.metalabs.io/signup/
Here is direct link to js code
http://ccn.metalabs.io/wp-content/themes/criticalcontactsnetwork/js/app.js
Could it be because a self signed SSL is used?
Thank you
Update 1: Here is the thing, I'm using vagrant to manage my dev environment, and when I tried to access my app via vagrant public URL $routeProvider suddenly worked. I think it has something to do with self-signed SSL certificate or some kind of browser policy
Update 2: Just disabled SSL, didn't helped. Weird, it works via vagrant shared URL, but does not work on my subdomain.
I figured out what was the problem. When I transferred wordpress database from dev to production Page Template option reset back to Default Template, so I didn't even had ng-view in html.
I have a code based on Angular js framework from google.
The code define some routing and associate views to the url path.
the code is like this
var profileModule = angular.module('profileModule', ['ngResource']);
profileModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'profileController',
templateUrl: 'Partials/profileList.html'
})
.otherwise({ redirectTo: '/' });
$routeProvider.when('/profile/:profileId', {
templateUrl: 'Partials/profileDetail.html',
controller: 'profileDetailController'
});
});
profileModule.controller('profileController', function($scope, profileFactory) {
$scope.profiles = [];
function init() {
$scope.profiles = profileFactory.query();
}
init();
});
profileModule.factory('profileFactory', function ($resource) {
return $resource("api/profiles/:Id", { Id: "#Id" }, { "update": { method: "PUT" } });
});
The code was using version 1.1.5 of Angular, and it was working fine.
But then I tried to use the newer version 1.2.3
and the code is not working on this version.
it is giving this error
[$injector:unpr] Unknown provider: $routeProvider
I looked on example on how to use routeProvider in 1.2.3
and I found this example from the web site
profileModule.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.....
I tried this , but still the same error
I am using Angular from the CDN network , and specifically from here
http://code.angularjs.org/1.2.3/angular-route.js
You need to depend on the ngRoute module as well:
var profileModule = angular.module('profileModule', ['ngResource', 'ngRoute']);
Since Angular v 1.2, they've separated the routing into a separate file, so you have to include it in your code and then inject it into your module.
You can find the latest version here (angular-route.js):
http://code.angularjs.org/1.2.3/