$window.location.href is undefined with angularjs - angularjs

I programme an application in ASP.NET MVC6, angularjs and Bootstap.
I want reload a page after bootstrap modal closing.
To do this, I use $window.location.href but it's undefined.
This is my method in angular Controller:
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
$window.location.href = '/';
}
}
All runs except the redirection.
I hope someone can help me . Any help is welcome.

you can use
$location.path('/');
instead of
$window.location.href = '/';

Try This -
$location.path('/').replace();
if(!$scope.$$phase) $scope.$apply()

I tried to redirect since a view and not a modal. It's work.
So I think it's redirect with my modal who create problem.
It's my full controller:
(function () {
'use strict';
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl)
.controller('CustomersGetCtrl', CustomersGetCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
/*---------------------------------------------------------------------------------
* Obtain Customer List
*--------------------------------------------------------------------------------*/
function getListCustomers()
{
var reqCustomers = $http.get('/api/Customers');
reqCustomers.success(function (dataResult) {
$scope.customers = dataResult;
});
return $scope.customers;
}
getListCustomers();
/*---------------------------------------------------------------------------------
* Obtain Customer by ID
*--------------------------------------------------------------------------------*/
function getCustomer(id) {
var reqGetCustomer = $http({ url: '/api/customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
return $scope.customer;
}
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
//This is that I tried to redirect
//$window.location.href = '/';
//$location.path('/').replace();
//if(!$scope.$phase) $scope.$apply
}
/*---------------------------------------------------------------------------------
* Manage Customer Details Modal
*--------------------------------------------------------------------------------*/
$scope.openDetails = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/details.html',
controller: $scope.modalDetails,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalDetails = function($scope, $modalInstance, id)
{
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
/*---------------------------------------------------------------------------------
* Manage Customer Edit Modal
*--------------------------------------------------------------------------------*/
$scope.openEdit = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/edit.html',
controller: $scope.modalEdit,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalEdit = function ($scope, $modalInstance, id) {
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
}
//Controller to redirect since View
CustomersGetCtrl.$inject = ['$scope', '$http', '$routeParams', '$window'];
function CustomersGetCtrl($scope, $http, $routeParams, $window)
{
function getCustomer()
{
var reqGetCustomer = $http({ url: '/api/customers/' + $routeParams.id, method: 'GET' })
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
}
getCustomer();
$scope.edit = function () {
$window.location.href = '/';
}
}
})();

I solved the problem by using ui.router instead of ng -router.

Related

separated controller from component

Component:
crudModule.js
var crudModule = angular.module('crudModule', ['ui.router', 'smart-table', 'ngCookies', 'ui.bootstrap', 'angularModalService', 'dialogs', 'remoteValidation']);
angular.module('crudModule').component('applicationInfo', {
templateUrl: 'infoApplication.html',
controller: 'applicationInfoCtrl'
});
applicationInfoCtrl.js:
var crudModule = angular.module('crudModule')
crudModule.controller('applicationInfoCtrl', ['httpService', '$scope', function($http, $scope, $cookies, $stateParams, httpService) {
httpService.httpGetRequest("http://localhost:8080/applications/" + $stateParams.id).then(function success(response) {
$scope.application = response.data;
});
$scope.getApiKey = function () {
httpService.httpGetRequest('http://localhost:8080/applications/generateApiKey').then(function success(response) {
$scope.application.apikey = response.data.apikey;
$scope.application.apisecret = response.data.apisecret
})
};
$scope.send = function (object, url) {
httpService.httpPostRequest(object, url + "/" + $stateParams.id).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
}).then(function success(response){
});
}
}]);
httpService.js:
var crudModule = angular.module('crudModule')
crudModule.factory('httpService', function($http) {
return {
httpGetRequest: function (url) {
return $http({
method: 'GET',
url: url
})
},
httpPostRequest: function (object, url){
return $http({
method:'POST',
url: url,
data: object
})
}
}
});
I am getting error:
Cannot read property 'httpGetRequest' of undefined.
I have injected my httpService and i dont find any mistakes yet
The problem is the order of parameters in your controller, it should be
crudModule.controller('applicationInfoCtrl', ['$http','httpService', '$scope','$cookies','$stateParams' function(http,httpService, $scope,$cookies,$stateParams) {
}

Angular route does not resolve service

I've been scratching my head over this one for a couple hours now, and after a good amount of searching I haven't found a helpful solution.
As the title state, my dependencies are not being resolved by Angular's route provider. This is the error:
Unknown provider: testServiceProvider <- testService <- testService
My compiled Javascript file (app.js) looks like this:
'use-strict';
var app = angular.module('test-app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
testService: function (testService) {
console.log(testService.message);
}
}
})
}]);
app.factory('apiService', ['$http', function ($http) {
function url(endpoint) {
return '/api/v1' + endpoint;
}
return {
user: {
authenticated: function () {
return $http({method: 'GET', url: url('/user/authenticated')});
},
login: function (token) {
return $http({method: 'GET', url: url('/user/login'), cache: false, headers: {
Authorization: 'Basic ' + token
}});
},
logout: function () {
return $http({method: 'GET', url: url('/user/logout')});
},
model: function () {
return $http({method: 'GET', url: url('/user/data')});
}
}
};
}]);
app.factory('testService', function () {
return {
message: 'Hello world'
};
});
app.controller('HomeController', ['$scope', '$http', function ($scope, $http, apiService, testService) {
$scope.user = {
authenticated: false,
error: '',
username: '',
password: ''
};
$scope.login_button = 'Log in';
$scope.isAuthenticated = function () {
return $scope.user.authenticated;
}
$scope.needsAuthentication = function () {
if (!$scope.user.authenticated) {
return true;
}
return false;
}
$scope.logIn = function ($event) {
$event.preventDefault();
$scope.login_button = 'Please wait...';
var token = btoa($scope.user.username + ':' + $scope.user.password);
apiService.user.login(token).then(function (success) {
$scope.user = success.data.user;
$scope.user.authenticated = true;
}, function (error) {
$scope.user.error = 'Please try logging in again.';
$scope.login_button = 'Log in';
});
};
}]);
As far as I can tell, everything should be resolving fine; am I missing or misunderstanding something?
I think the problem in an alias. You use testService as alias for your resolving. $injector could be confused. Try to rename it for example:
resolve: { testData: function (testService) { console.log(testService.message); } }
and rename it in controller as well.
You have to inject the service,
change
From:
app.controller('HomeController', ['$scope', '$http', function ($scope, $http, apiService, testService)
To:
app.controller('HomeController', ['$scope', '$http','apiService','testService' ,function ($scope, $http, apiService, testService)

How to make a service call with a Angular-ui modal instance

I am switching to a Angular-ui modal and I am confused on how to make a $http get call and return the results. I have been using a different angular modal with the current code. I understand ow this is working but I need some help on the transition. thanks
This is the modal I am currently using. this works fine. I need to apply this to the Angular-UI modal
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
$scope.openEditCivilCaseModal = $ekathuwa.modal({
scope: $scope,
contentPreSize: "lg",
templateURL: "views/modals/editCivilCaseModal.html"
});
//show modal window
$scope.openEditCivilCaseModal.then(function (m) {
m.modal('show');
});
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
need to switch to this
.controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ["item1", "item2", "item3"];
$scope.open = function (id) {
var modalInstance = $modal.open({
templateUrl: "views/modals/editCivilCaseModal.html",
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then((function (selectedItem) {
$scope.selected = selectedItem;
}), function () {
$log.info("Modal dismissed at: " + new Date());
});
};
}
).controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
}
Solution per the suggested solution
//Edit Civil Modal
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
}).error(function (error) {
deferred.reject(error);
}).then(function () {
$modal.open({
templateUrl: "views/modals/editCivilCaseModal.html",
controller: 'ModalInstanceCtrl',
resolve: {
active: function () {
return $scope.active;
}
}
});
})
return deferred.promise;
}
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, active) {
$scope.active = active
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
});
you should split your $http call
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
and on success of http do whatever you like opening the model.
$scope.editCivilCaseModel().then(function(){
$scope.openEditCivilCaseModal = $ekathuwa.modal({
scope: $scope,
contentPreSize: "lg",
templateURL: "views/modals/editCivilCaseModal.html"
});
//show modal window
$scope.openEditCivilCaseModal.then(function (m) {
m.modal('show');
});
})
this is just to give you the concept because I am not able to see the exact relationship between now and expected.

Angular controller won't update the view for some reason

I have a service that looks like:
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({
url: '/api/v1/peers',
method: 'GET'
});
};
}
]);
In my controller, I have:
myApp.controller('PeerComparisonController', [
'$scope', '$rootScope', 'peerService', function($scope, $rootScope, peerService) {
$scope.init = function() {
$rootScope.pageTitle = 'Peer Comparison';
return $scope.peers = [];
};
$scope.getPeers = function() {
return peerService.getPeers().then(function(response) {
console.log(response);
return $scope.peers = response.data;
});
};
return $scope.init();
}
]);
My view has {{ peers }} in it. This does not get updated when the service returns. I've tried:
peerService.getPeers().then(function(response) {
return $scope.$apply(function() {
return $scope.peers = response.data;
});
});
And that also doesn't work. So any ideas?
you try something like this
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({method: 'GET', url:'/api/v1/peers'}).
then(function(response) {
return response.data;
});
};
}
]);
or
myApp.service('peerService', ['$http', function ($http) {
this.getPeers = function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/api/v1/peers' }).
then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
};
}
]);

Angularjs $on not firing after $rootScope.$broadcast

I have this code where two controllers are using a shared service to communicate.
var app = angular.module('AdminApp', ['ngRoute']);
app.factory('SharedService', function ($rootScope) {
var sharedService = {
userId: [],
BroadcastUserId: function (id) {
this.userId.push(id);
$rootScope.$broadcast('handleBroadcast');
}
};
return sharedService;
});
app.config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: "adminLogin.html"
});
$routeProvider.when('/main', {
templateUrl: 'adminMain.html'
});
$routeProvider.otherwise({
redirectTo: '/login'
});
});
app.controller('authCtrl', function ($scope, $http, $location, SharedService) {
$scope.Userid = '';
$scope.authenticate = function (user, pass) {
$http.post('http://localhost/NancyAPI/auth', {
UserName: user,
Password: pass
}).success(function (data) {
$scope.$broadcast('Token', data.Token);
$http.defaults.headers.common['Authorization'] = 'Token ' + data.Token;
$scope.Userid = data.UserId;
SharedService.BroadcastUserId($scope.Userid);
$location.path("/main");
}).error(function (response) {
$scope.authenticationError = response.error || response;
});
};
$scope.$on('handleBroadcast', function () {
console.log('on');
});
}).$inject = ['$scope', '$rootScope', 'SharedService'];
app.controller('mainCtrl', function ($scope, $http, $q, SharedService) {
$scope.tests = [];
$scope.userId = -1;
$scope.getTests = function () {
var deferred = $q.defer();
$http.get('http://localhost/NancyAPI/auth/tests/' + $scope.userId).
success(function (data) {
deferred.resolve(data);
$scope.tests = angular.fromJson(data);
}).error(function (response) {
});
};
// THIS IS NOT FIRING
$scope.$on('handleBroadcast', function () {
$scope.userId = SharedService.userId;
});
}).$inject = ['$scope', '$rootScope', 'SharedService'];
For some reason the $scope.$on is firing in the AuthCtrl controller but not in the mainCtrl.
// THIS IS NOT FIRING
$scope.$on('handleBroadcast', function () {
$scope.userId = SharedService.userId;
});
Why is this happening and how do I fix it?
I made a subtle mistake of not providing the {$rootScope} as dependency. Once I corrected that, it worked for me. I used Inline Array Annotation mechanism to achieve the same.

Resources