Is there a way to inject automatically a dependency (or a resolve) in the $scope without manually append it to $scope ?
(with or without UI-Router)
Would the "controllerAs" syntax be of any help ?
.config(['$stateProvider',
function($stateProvider) {
$stateProvider
.state('test', {
url: '/test',
templateUrl: 'test.tpl.html',
controller: 'TestCtrl',
})
;
}
])
.controller('TestCtrl', ['$scope', 'myService',
function($scope, $rootScope, accruals, myService) {
$scope.myService= myService; // how can I avoid this every time ?
}
])
Thanks
Related
I am trying to have a link in my page such as:
<a ng-href="#/Page/{{x.ID}}">{{x.ID}}</a>
Which succesfully gets to the angular controller but however the $routeparams are null when I am expecting to get the {{ x.ID }} back:
pageController.js
angular.module("myApp.Pages").controller("pageController", ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);
And am referencing the state in my $stateprovider such as (in appRouting.js):
$stateprovider.state('Page', {
url: '/Page/:userId',
templateUrl: 'App/Pages/page.html',
controller: 'pageController'
})
my app.js
angular.module("myApp", [
// User defined modules
'myApp.Pages', // Pages
'myApp.Core', // Core
// Angular modules
'ui.router', // state routing
'ngRoute', // angular routing
'LocalStorageModule', //local browser storage
'angularRangeSlider',
'ngFileUpload'
])
Any ideas?
$stateParams instead of $routeParams
I need to switch view in my angular js webapp.
In order to handle the routing, I am using the $stateProvider, as here:
.config(['$httpProvider', '$stateProvider', '$urlRouterProvider', function ($httpProvider, $stateProvider, $urlRouterProvider) {
$stateProvider
.state('common', {
templateUrl: 'assets/html/template.html',
abstract: true,
})
.state('login', {
url: '/login',
parent: 'common',
templateUrl: 'app/models/authentication/views/login.html',
controller: 'LoginController'
})
.state('home', {
url: '/',
parent: 'common',
templateUrl: 'app/models/home/views/home.html',
controller: 'HomeController'
})
...
Inside my login controller, I am trying to switch the view (from Login to Home)
.controller('LoginController', ['$scope', '$rootScope', '$cookieStore', '$location', '$window', '$http',
function ($scope, $rootScope, $cookieStore, $location, $window, $http) {
$scope.login = function () {
loadHttp();
};
function loadHttp() {
var url = "http://myurl";
...
.then(function (response) {
$scope.$apply(function () {
$location.path('/home');
console.log("$location.path: " + $location.path);
});
});
}
But when I reach $location.path('/home'); I get this error:
Error: [$rootScope:inprog] http://errors.angularjs.org/1.4.8/$rootScope/inprog?p0=%24digest
at Error (native)
at http://localhost:3000/adminTool/assets/js/angular.min.js:6:416
at t (http://localhost:3000/adminTool/assets/js/angular.min.js:126:132)
at r.$apply (http://localhost:3000/adminTool/assets/js/angular.min.js:133:515)
at http://localhost:3000/adminTool/app/models/authentication/controllers.js:46:32
at http://localhost:3000/adminTool/assets/js/angular.min.js:119:129
at r.$eval (http://localhost:3000/adminTool/assets/js/angular.min.js:133:313)
at r.$digest (http://localhost:3000/adminTool/assets/js/angular.min.js:130:412)
at r.$apply (http://localhost:3000/adminTool/assets/js/angular.min.js:134:78)
at g (http://localhost:3000/adminTool/assets/js/angular.min.js:87:444)
What am I doing wrong? How to get rid of it and finally switch view?
I read to use $apply from SO
PS: I am very new to angular
The error you get is because of the $scope.$apply around the $location.path('/home') statement. Angular is already in a digest loop so triggering it again within that loop (by calling $apply) will give you this error. Removing the $scope.$apply will therefor probably fix your problem.
The reason the digest loop is already triggered is because you are probably using the $http service which uses a promise to return the value. Angular always triggers a digest when resolving this promise.
But aside from that you probaly want to use the $state service to move to another state instead of moving to another location using the $location service. $state.go('home') would probably be what you are looking for.
I think here is the problem $location.path('/home');
You don't have path /home you have state called home
so you need to go $location.path('/'); or inject $state and use method $state.go('home'), also you do not need to wrap it inside $apply
I am trying to access $scope variable inside my controller . when I console my $scope it shows number of values but when I try to access it via $scope. it return undefined.
I have attached screen shot of $scope
Here you can see it have $id, $parent , templateUrl but when i am trying to access it via $scope.id , $scope.parent , $scope.templateUrl it return undefined .
Edited :
I am trying to access template url . actually I want to attach some params with template url so that I can get them in my backend function
here is my code :
brainframeApp.config(
['$interpolateProvider', '$locationProvider', '$httpProvider', '$routeProvider',
function($interpolateProvider, $locationProvider, $httpProvider,
$routeProvider) {
//configuring angularjs symbos to not to conflict with Django template symbols
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
//$locationProvider.html5Mode(true).hashPrefix('!');
// setup CSRF support
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
console.log("TestDavy: App");
//The route provider
$routeProvider.
when('/', {
templateUrl: '/static/engine/partials/listbrainframes.html',
controller: 'brainframeCtrl'
}).
when('/brainframe/', {
templateUrl: '/views/post.html',
controller: 'brainframeCtrlx'
}).
when('/brainframe/:id', {
templateUrl: '/views/post.html',
controller: 'brainframeCtrlx'
}).
otherwise({
redirectTo: '/'
});
}]);
my controller :
brainframeAppControllers.controller('brainframeCtrlx',
['$scope', '$routeParams', function($scope, $routeParams) {
//console.log($scope.parent);
//$scope.templateUrl = 'views/post.html?id='+$routeParams.id;
//console.log($scope);
$scope.templateUrl = 'views/post.html?id='+$routeParams.id;
//console.log($scope.templateUrl);
}]);
When I put console.log on $scope, am able to see only these properties:
["$$childTail", "$$childHead", "$$nextSibling", "$$watchers", "$$listeners", "$$listenerCount", "$id", "$$ChildScope", "$parent", "$$prevSibling"]
If you want to access the template URL inside your controller:
brainframeApp.run(function($rootScope) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
$rootScope.templateUrl = next.$$route.templateUrl;
});
});
Now inside your controller, inject $rootScope and get the template URL
$rootScope.templateUrl
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 experimenting with $routeParams, by following along with this example in the AngularJS documentation. For reference, here is the script itself:
angular.module('ngRouteExample', ['ngRoute'])
.controller('MainController', function($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})
.controller('BookController', function($scope, $routeParams) {
$scope.name = "BookController";
$scope.params = $routeParams;
})
.controller('ChapterController', function($scope, $routeParams) {
$scope.name = "ChapterController";
$scope.params = $routeParams;
})
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterController'
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
What I can't understand is this: how does MainController get the updated $routeParam object? I can see that as I click, items that MainController is responsible for setting are changing, but I don't understand how. It's making it a little tough to reproduce this behavior.
It doesn't get re-instantiated, and it's not "getting" the updated $routeParams object - the object in the controller is the routeParams object. It is the same object that is in the other controllers, not a "copy" of it.
So when the $routeParams object gets changed, the other controller already has the changes.