AngularJs. $location service. Url modification - javascript

Suppose, I have follwing code with AngularJs:
angular.module('somename', []).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/test/:userid', { controller: TestDataCtrl }).
when('/users/:userid', {controller: UserDataCtrl}).
otherwise({redirectTo: '/index.html'});
$location.path('/newValue')
});
But this fragment throws ReferenceError: $location is not defined from archivarius. Ok, no problem. I added third parameter $location to the function and got error -- Unknown provider: $location from archivarius.
So, how can I get instance of $location service?
In other words, I have some ugly url like:
http://localhost:7000/myservice/1?html=true#/index
and my routes above doesn't work, because it is supposed
that service url looks like
http://localhost:7000/myservice/#/index
or
http://localhost:7000/myservice/index
But because of my internal redirect logic of REST service I came up with
a little bit confusing url for AngularJs and I need to change it without page reload.
Thanks in advance.

Add the `$location' object to you config unanimous function:
config(function ($routeProvider, $locationProvider, $location)
Hope it helps

Related

Injecting Angular modules: Unknown provider

I followed a tutorial on how to organize and Angular project. I have a ng directory that contains all my controllers, services and my routes.js. This is then bundled all together into an app.js by my gulp config.
My module.js is like this:
var app = angular.module('app', [
'ngRoute',
'ui.bootstrap'
]);
Here's a bit of my routes.js:
angular.module('app')
.config(function ($routeProvider) {
.when('/login', { controller: 'LoginCtrl', templateUrl: 'login.html'})
});
Here's what my working LoginCtrl looks like:
angular.module('app')
.controller('LoginCtrl', function($scope, UserSvc) {
$scope.login = function(username, password) {
...
}
})
The tutorial didn't make use of any Angular modules and I wanted to try one out. I added ui.bootstrap to my page from a CDN and try to change the LoginCtrl to:
angular.module('app')
.controller('LoginCtrl', function($scope, $uibModal, UserSvc) {
...
})
But this throws me the following error:
"Error: [$injector:unpr] Unknown provider: $templateRequestProvider <- $templateRequest <- $uibModal
What is causing this error? In every tutorial I find this seems to be how they load a module, the only difference I see is that the tutorial don't seem to be using a router.
PS: Note that if I use an empty module list [] I get the exact same error. If I use a non-existing module ['helloworld'] I get an errorModule 'helloworld' is not available'. So I'm concluding that my `ui.bootstrap' module is indeed available.
EDIT: Plunker fiddle here: http://plnkr.co/edit/FWHQ5ZDAByOWsL9YeMUH?p=preview
angular route is another module you should not only include but also use like this
in the app module creation
means DI of route
angular.module('app', ['ngRoute']);
Please go through the angular route doc
Remove ['ui.bootstrap'] form controller. You should add dependencies only one time but you add it twice so the second dependency list override the first one.
angular.module('app')
.controller('LoginCtrl', function($scope, UserSvc) {
... })
your routes snippet looks wrong, you should be hanging the when call off $routeProvider and maybe declare $routeProvider as an injected val if it's not being picked up e.g.
angular.module('app')
.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when('/login', { controller: 'LoginCtrl', templateUrl: 'login.html'})
}]);
I have checked your link. I think there is a serious issue with angular and ui bootstrap version.In ui-boostrap dashboard, it is written that 0.12.0 is the last version that supports AngularJS 1.2.x. I have tried with all combinations but it doesn't work with your angular version.
I suggest you to change angular version to latest and ui-bootstrap version to latest so it will work.
Please check out this working Plukr
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.js'></script> //change this to latest also.
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.0.3/ui-bootstrap.min.js'></script>
<script src='./app.js'></script>
If you want to go with your angular version only. I'd request you to do some R&D. Try with different versions of ui-bootstrap. still if it doesn't work you can make PR.

html5mode doesn't remove hashbangs

I have a gulp connect server running and want to remove hashbangs from the routeProvider I am using in my AngularJS project.
I have this in my app.js:
//Setting HTML5 Location Mode
companiesApp.config(['$locationProvider',
function ($locationProvider) {
$locationProvider.hashPrefix('!');
$locationProvider.html5Mode(true);
}
]);
I know that if I remove the hashPrefix it will work still with http://www.example.com/#example-uri but how do I get rid of that entirely. isn't html5Mode(true) supposed to do that?
Yes, $locationProvider.html5Mode(true); should do that.
But to be able to access pages directly from the browser, you should configure your server to redirect the request to the index page, then call the partial internally. Check this document on angular-ui documentation for how to configure the document to do so.
Try this if may be useful in your scenario
Add only has prefix like $locationProvider.hashPrefix('') to remove Bang prefix...
var app = angular.module('app', []);
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider)
{
$routeProvider.when('/', {
templateUrl: "app1.html",
controller: "App1Ctrl"
})
.when('/Program1', {
templateUrl: "app2.html",
controller: "App2Ctrl"
});
$locationProvider.hashPrefix("");
}
]);
first add $routeProvider in dependency and then add in last of hashPrefix is null
to remove tha bang prefix.

Stop Controller's activity when switch route

I create single page app by AngularJS and I found my problem. I have function refresh data every 2 minutes by jQuery in route A. When I change to other route, that function in controller is still working. This is my code.
App.js
var newsapp = angular.module('newsAppMD', ['ngRoute']);
newsapp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/news', {
templateUrl: 'templates/news.html',
controller: 'imageNewsCtrl'
}).
when('/news/:nameCat', {
templateUrl: 'templates/news-thumbnail.html',
controller: 'newsPageCtrl'
}).
otherwise({
redirectTo: '/news'
});
}]);
newsapp.controller('imageNewsCtrl', function($scope, $http, $interval, $timeout ) {
$('#bottom-bar').find('#epg').hide();
$scope.updateTimeEPG = 120000;
$scope.fetchFeed = function() {
$http.get("http://wi.th/thaipbs_tv_backend/epg_forJS.php").success(function(response) {
$scope.items = response.Schedule;
console.log($scope.items);
$timeout(function() { $scope.fetchFeed(); }, $scope.updateTimeEPG);
}).then(function() {
$('#bottom-bar').find('.loading').hide();
$('#bottom-bar').find('#epg').show();
});
};
$scope.fetchFeed();
});
newsapp.controller('newsPageCtrl', function($scope, $http, $location) {
// blah blah blah
}]);
I choose /news imageNewsCtrl work. And when I switch to other route, function in imageNewsCtrl still work (I see function print console.log when I changed route). I want to stop function in controller when change route. Thanks for your suggestion everyone. :)
I am not too entirely sure, but try using $stateProvider instead of $routeProvider. If you do, then you need to npm install angular-ui-router (it is a powerful third party module) and replace ngroute. I only user $routeProvider for the .otherwise function. You can also do a lot more cool stuff like onEnter and onExit with $stateProvider. Another thing is I would recommend you to use only Angular instead of jQuery. I do not really see a point of you using both. Use Angular's two-way data binding! Also, if you really want to get into Angular, then I recommend John Papa's style guide. This guys knows what he is talking about for making a great Angular app. I hope this info helps!

Trying to get my Resolve to inject into my controller to be able to inject into the HTML

This is my index.js file
'use strict';
angular.module('wildenglish', ['ngAnimate', 'ngTouch', 'restangular', 'ngRoute', 'ui.bootstrap'])
.config(function ($routeProvider, RestangularProvider) {
RestangularProvider.setBaseUrl('https://www.googleapis.com/calendar/v3/calendars/googleCalendarID');
$routeProvider
.when('/', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl',
resolve: {
calendarEvents: function(Restangular){
return Restangular.one('eventsAUTHKEY').get();
}
}
})
.otherwise({
redirectTo: '/'
});
})
And my main controller.js
'use strict';
angular.module('wildenglish')
.controller('MainCtrl', function(Restangular, calendarEvents) {
var self = this,
events = calendarEvents,
items = events.items;
});
The Error I'm receiving when I try to use in the HTML is:
Error: [$injector:unpr] Unknown provider: calendarEventsProvider <- calendarEvents <- MainCtrl
So I am trying to figure out how I can utilize the information that I am getting back from that Promise which I can log in the console to be accessible to the HTML via the controller
Do I need a service or factory? and where would that go?
Thank you in advance for your help
Assign the events returned by the resolved promise to your controller scope. You'll need to change the depencies your injecting into your controller. You can leave out Restangular since you are resolving your promise in your route but you do need $scope:
angular.module('wildenglish').controller('MainCtrl', function($scope, calendarEvents) {
// i'm assuming the following logs your events to your console
// if not you're having a problem with your Restangular request
console.log(calendarEvents);
// Assign calendarEvents to your $scope
$scope.events = calendarEvents;
});
Now you can use the events in your HTML template (assuming each event has a property called 'name'):
<ul>
<li ng-repeat="event in events">{{event.name}}</li>
</ul>
Sorry, I missed the answer above which is already the correct answer.
There was a similar problem here:
AngularJS, resolve and unknown provider
Basically if you are using the routeProvider to assign your controller in your script file you cannot use ng-controller in your template.

Configure AngularJS routes to deep path using $window

I have a Rails app which has some complex routing. My Angular application exists in a deep URL such as /quizzes/1
I was hoping to do this the Angular was by injecting $window into my routes configuration and then sniffing $window.location.pathName. This does not seem possible as the application throws an "Unknown provider: $window from myApp" at this stage.
Is there a best-practice way to handle this with Angular? The reason I would like to do this is to use HTML5 mode while the app lives in a deep directory.
Here's an example of what I was hoping for, http://jsfiddle.net/UwhWN/. I realize that I can use window.location.pathname at this point in the program if it's the only option.
HTML:
<div ng-app="myApp"></div>
JS:
var app = angular.module('myApp', [])
app.config([
'$window', '$routeProvider', '$locationProvider',
function($window, $routeProvider, $locationProvider) {
var path = $window.location.pathname
// Coming Soon
// $locationProvider.html5Mode(true)
$routeProvider
.when(path + '/start', {
controller: 'splashScreenController',
templateUrl: 'partials/splash-screen.html'
})
.when(path + '/question/:id', {
controller: 'questionController',
templateUrl: 'partials/question-loader.html'
})
.otherwise({
redirectTo: path + '/start'
})
}])
Only constants and providers can be injected into config block. $window isn't injectable into your config block because $window is a service.
From Angular docs:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
And, you don't need $window service there anyway. Just use <base> tag:
<base href="/quizzes/1/" />
and keep your routes relative to it.

Categories