Dynamic injection angularjs? - javascript

i am using one of the basic concept of angularjs that child controller inherit from parent controller. so i have writen the following code :
var editChannelCtrl = function ($scope, $route, $location, youtube) {
$scope.loading = false;
$scope.saved = false;
$scope.errors = [];
if (angular.isDefined($route.current.params.id)) {
$scope.isOldChannel = true;
$scope.isNewChannel = false;
} else {
$scope.isNewChannel = true;
$scope.isOldChannel = false;
}
};
editChannelCtrl.$inject = ['$scope', '$route', '$location', 'youtube'];
editChannelCtrl.resolve = {
channel: ['ServiceChannel' , function (ServiceChannel) {
return ServiceChannel.ChannelLoader();
}]
};
var oldChannelCtrl = function ($scope, $location, channel) {
$scope.channel = channel;
};
oldChannelCtrl.$inject = ['$scope' , '$location', 'channel'];
var newChannelCtrl = function ($scope, $location, Channel) {
$scope.channel = {
id: null,
version: 1
};
};
newChannelCtrl.$inject = ['$scope' , '$location', 'Channel'];
and for routes what i do , that i resolve the channel that load the channel for the edit form with the following code.
.when('/admin/refactor/channel/edit/:id', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html',
resolve: editChannelCtrl.resolve
})
.when('/admin/refactor/channel/new', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html'
})
but i don't know why angularjs don't figure how to inject channel to oldChannelCtrl ?

Related

Share value between views in AngularJS

I have apage with 3 options and each option represent a group of permissions. I have the groupName in my view permissionsConfig but when I edit one group I lose the name of the group and i need the name to make a request to my rest api.
organizationsController.js
app.controller('OrganizationsPermissionsSettingsController',['$rootScope', '$scope', '$modal', 'HelperService', 'AuthService', '$state', '$http', function ($rootScope, $scope, $modal, HelperService, AuthService, $state, $http) {
var controllerScope = $scope;
controllerScope.organizationGroups = [];
$http.get('/api/organization_permissions_groups').success(function (data) {
controllerScope.organizationGroups = data;
});
controllerScope.openOrganizationPermissionsSettings = function (organizationId) {
$state.go('app.organizationPermissionsSettings');
};
var groupId = "";
document.addEventListener("DOMContentLoaded", function(event) {
if(document.getElementById("permissionGroupName").innerHTML!=null){
groupName=document.getElementById("permissionGroupName").innerHTML;
console.log("groupName ",groupName);
$http.get('/api/organization_permissions_groups/getId'+groupName).success(function (data) {
if(data != undefined && data != null){
groupId=data;
console.log("controllerScope.id ",groupId);
}
});
}
});
$scope.navigateToGraphs = function() {
$state.go('app.organizationGraphs', { groupId: groupId });
// then get parameter groupId
$state.params.groupId;
}
$scope.navigateToViews = function() {
$state.go('app.organizationViews', { groupId: groupId });
// then get parameter groupId
$state.params.groupId;
}
}]);
app.controller('OrganizationGraphsController',['$rootScope', '$scope', 'HelperService', '$http', '$stateParams', function ($rootScope, $scope, HelperService, $http, $stateParams) {
var controllerScope = $scope;
controllerScope.graphData = {};
$http.get('/api/organization_permissions_groups/graphs/'+$stateParams.groupId).success(function (data) {
controllerScope.graphData = data.graphs;
});
controllerScope.saveOptions = function () {
$http.put('/api/organization_permissions_groups/graphs/'+$stateParams.groupId, controllerScope.graphData).then(function (response) {
}, function () { });
HelperService.editItem(id, controllerScope.graphData, null, 'Graphs', '/api/organization_permissions_groups/graphs/');
}
$scope.cancel = function () {
$modalInstance.dismiss();
};
}
]);
organizationPermissionsConfigView.html
here I have <td id="permissionGroupName">{{organizationGroup.group_name}}</td> which retrive my permission group name.
I have 3 groups at the moment and with the group name i make a rest api request to get the id and with that id i can make updates on the permission group understand?

How to call $resource custom method in controller

I have a factory:
myService:
'use strict';
app.factory('myService', ['$resource', 'ngAuthSettings', function ($resource, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
return $resource(serviceBase + 'api/category/', {}, {
update: {
method: 'PUT'
},
getAllByCategory: {
url: serviceBase + 'api/category/GetAllByCategory',
method: 'GET', isArray: true
}
});
}]);
Then I have a controller:
searchController:
'use strict';
app.controller('searchController',
['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
function (ngAuthSettings, $scope, myService, $routeParams, $location) {
function init() {
var search = $location.search();
var keywords = search.keywords;
var model = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page });
$scope.categoryAds = model.ads;
$scope.bigTotalItems = model.totalCount;
$scope.maxSize = ngAuthSettings.maxPagingSize;
}
init();
}]);
Why my model.ads is always undefined? Isn't this the right way to call $resource custom method in controller?
As response may take some time but you are adding assignment very immediatly hence it happening put it in promise/action after resource,
'use strict';
app.controller('searchController', ['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
function (ngAuthSettings, $scope, myService, $routeParams, $location) {
function init() {
var search = $location.search();
var keywords = search.keywords;
var model = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page },
function() {
$scope.categoryAds = model.ads;
$scope.bigTotalItems = model.totalCount;
$scope.maxSize = ngAuthSettings.maxPagingSize;
}
);
}
init();
}
]);

angularjs When I refresh my page it redirects me to login page

Hi after setting up Spring Security, the login works fin for me.But when I refresh anypage it redirects me to login page. How Can I get rid of this.
Here is my code
config.js
'use strict';
var app = angular.module('MyApp', [ 'ngResource', 'ngRoute',
'myAppControllers', 'ngAnimate', 'ui.bootstrap', 'ngCookies' ]);
app.config(function($routeProvider) {
$routeProvider.when('/products/:idCat', {
templateUrl : '../views/partials/products.html',
controller : 'ProductsController'
}).when('/products', {
templateUrl : '../views/partials/allProducts.html',
controller : 'ProductsController'
}).when('/supprimer', {
templateUrl : '../views/partials/delete.html',
}).when('/update', {
templateUrl : '../views/partials/update.html',
controller : 'UserController'
}).when('/client', {
templateUrl : '../views/partials/client.html',
controller : 'ClientController'
}).when('/agences', {
templateUrl : '../views/partials/agences.html',
controller : 'MapController'
}).when('/login', {
templateUrl : '../views/partials/login.html',
controller : 'mainController'
}).when('/', {
templateUrl : '../views/partials/Home.html',
})
$routeProvider.otherwise('/');
});
app.run(function($route, $rootScope, $http, $location, $cookieStore,
$anchorScroll) {
$rootScope.authenticated = false;
$rootScope.$on('$routeChangeStart', function() {
var originalPath = $location.url();
if ($rootScope.authenticated == false) {
$location.path('/login');
} else {
$rootScope.redirectUrl = angular.copy($location.url());
var user = $cookieStore.get('user');
if (user !== undefined) {
$rootScope.user = user;
$http.defaults.headers.common['X-Auth-Token'] = user.token;
$location.url(originalPath);}})
});
my app.js where I have my controller ang call for authenticate Service
myAppControllers
.controller(
'mainController',
function($scope, $rootScope, loginService, ProductService,
$location, $cookies, $cookieStore, $http) {
$rootScope.salesAgent = true;
$scope.loggedIn = false;
$rootScope.hasRole = function(role) {
if ($rootScope.user === undefined) {
return false;
}
if ($rootScope.user.authorities === undefined) {
return false;
}
for (var i = 0; i < $rootScope.user.authorities.length; i++) {
if ($rootScope.user.authorities[i].authority == role)
return true;
}
return false;
};
$scope.logout = function() {
console.log("Testtttttttttt");
delete $rootScope.user;
delete $http.defaults.headers.common['X-Auth-Token'];
$cookieStore.remove('user');
$location.url("/login");
};
$scope.authenticate = function() {
loginService
.authenticate($scope.username,
$scope.password)
.then(
function(user) {
$rootScope.user = user;
$http.defaults.headers.common['X-Auth-Token'] = user.token;
$cookieStore.put('user',
user);
if ($rootScope.redirectUrl != null
&& $rootScope.redirectUrl
.indexOf('/') == -1)
$location
.url($rootScope.redirectUrl);
else {
$rootScope.authenticated = true;
$location.path("/");
}
$rootScope.redirectUrl = null;
$rootScope.redirectStatus = null;
}),
function err(data) {
if ($rootScope.redirectStatus == 401)
}
};});
I'll be pleased for your help!
You are storing authenticated value in $rootScope after refreshing it is getting nullified, instead of that use $cookieStore for angular 1.2 or less, or $cookies for angular 1.2 or above.
You are using $cookieStore for user, do the same for authenticated
$cookieStore.put('authenticated',$rootScope.authenticated);
Check if the cookie exists as a first step in run
app.run(function($route, $rootScope, $http, $location, $cookieStore, $anchorScroll) {
var user = $cookieStore.get('user');
if (user !== undefined) {
// set up X- header and other variables here
Another option is to store the authentication value in the localStorage:
localStorage.setItem ('session.authenticated', true);
Then you can get the authentication value as follows:
localStorage.getItem("session.authenticated") || false;

AngularJS variable not showing in html

Structure
statsController.js
(function (module) {
'use strict';
var statsController = function ($scope, $rootScope, $timeout, $routeParams, $location, $window, statsService) {
$scope.$on('$viewContentLoaded', function (event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
var model = {};
model.stats = {};
statsService.getStats().then(function (d) {
model.stats = d;
});
};
module.controller("statsController", statsController);
}(angular.module("app")));
statsService.js
(function (app) {
var statsService = function (webapi) {
var model = {};
model.getStats = function () {
return webapi.get('stats/getstats');
}
return model;
};
app.factory("statsService", statsService);
statsService.$inject = ['webapi'];
}(angular.module("app")))
stats.html
Total paid customers: {{statsController.model.totalPaidCustomers}}<br/>
Stripe confirmed customers: {{statsController.model.stripeConfirmedCustomers}}<br />
Result from API:
{"totalPaidCustomers":1,"stripeConfirmedCustomers":2}
When I put alert() in statsController.js for d.totalPaidCustomers I get value 1, same for other parameter.
So only problem is to show this in html.
App.js
.when('/stats', {
templateUrl: 'tpl/admin/stats.html',
controller: 'statsController',
controllerAs: 'stats'
}).
If i understand correctly. It should be "model.stats"
Total paid customers: {{statsController.model.totalPaidCustomers}}
http://jsfiddle.net/f5hb9spz/8/
Try changing your state definition to this:
.when('/stats', {
templateUrl: 'tpl/admin/stats.html',
controller: 'statsController',
controllerAs: 'vm'
}).
Then change the controller to this:
(function (module) {
'use strict';
var statsController = function ($scope, $rootScope, $timeout, $routeParams, $location, $window, statsService) {
$scope.$on('$viewContentLoaded', function (event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
var vm = this;
vm.model = {};
vm.model.stats = {};
statsService.getStats().then(function (d) {
vm.model.stats = d;
});
};
module.controller("statsController", statsController);
}(angular.module("app")));
Finally your view goes to this:
Total paid customers: {{vm.model.stats.totalPaidCustomers}}<br/>
Stripe confirmed customers: {{vm.model.stats.stripeConfirmedCustomers}}<br />
If you don't see anything then just put this in the view and see what you have:
{{ vm | json }}
Problem was I didn't assign the current scope to a model.
var model = this;
statsController.js
(function (module) {
'use strict';
var statsController = function ($scope, $rootScope, $timeout, $routeParams, $location, $window, statsService) {
$scope.$on('$viewContentLoaded', function (event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
var model = this;
model.stats = {};
statsService.getStats().then(function (d) {
model.stats = d;
});
};
module.controller("statsController", statsController);
}(angular.module("app")));
Then call in html:
Total paid customers: {{stats.stats.totalPaidCustomers}}<br/>
Stripe confirmed customers: {{stats.stats.stripeConfirmedCustomers}}<br />
have to change name of var though(stats.stats), confused the hell out of me.

AngularJS expected information not displaying

I am working on a mobile application that gets a list of jobs from the server (WEBAPI) and populates the proper fields. When the user clicks on the job name, the application goes to a details page, where the job information needs to show again.
I am having issues getting the information to show.
Here is the index:
.state('jobs',{
abstract: true,
url: '/jobs',
templateUrl: 'modules/jobs/views/jobs.html',
controller: ['$scope', '$state', '$stateParams', 'jobs', function($scope, $state, $stateParams, jobs) {
jobs.getData()
.then(function(jobs) {
$scope.jobs = jobs;
});
}]
})
// Jobs > List
.state('jobs.list', {
url: '',
title: 'All Jobs',
templateUrl: 'modules/jobs/views/jobs.list.html'
})
// Jobs > Detail
.state('jobs.detail', {
url: '/{JobId:[0-9]{1,4}}',
title: 'Job Details',
views: {
'details': {
templateUrl: 'modules/jobs/views/jobs.detail.html',
controller: ['$scope', '$state', '$stateParams', 'utils', function($scope, $state, $stateParams, utils) {
$scope.job = utils.findById($scope.jobs, $stateParams.JobId);
$scope.edit = function(){
$state.go('.edit', $stateParams);
};
}]
},
'': {
templateUrl: 'modules/jobs/views/jobs.materials.html',
controller: ['$scope', 'materials', '$stateParams', function($scope, materials, $stateParams) {
materials.getDataById($stateParams.JobId)
.then(function(materials) {
$scope.materials = materials;
});
$scope.subHeader = 'Bulk Sack Materials';
}]
}
}
})
Here is the Service:
app.factory('jobs', ['$resource', '$q', '$http', 'localStorageService', function($resource, $q, $http, localStorageService) {
localStorageService.set('SessionId', 'A00DB328-7F9C-4517-AD5D-8EAA16FBBC8F');
var SessionId = localStorageService.get('SessionId');
return {
getData: function() {
var deferred = $q.defer();
$http.get(baseUrl + 'Job/GetJobs?SessionId=' + SessionId, {
cache: true
}).success(function(jobs) {
deferred.resolve(jobs);
});
return deferred.promise;
}
};
}]);
app.factory('materials', ['$resource', '$q', '$http', 'localStorageService', function($resource, $q, $http, localStorageService) {
var SessionId = localStorageService.get('SessionId');
return {
getDataById: function(id) {
var deferred = $q.defer();
$http.get(baseUrl + 'Material/GetMaterials/' + id + '?SessionId=' + SessionId, {
cached: 'true'
}).success(function(materials) {
deferred.resolve(materials);
});
return deferred.promise;
}
};
}]);
And here is the utils service:
app.factory('utils', function() {
return {
findById: function findById(a, id) {
for (var i = 0; i < a.length; i++) {
if(a[i].id === id) {
return a[i];
}
}
return null;
}
};
});
Here is the HTML for the job.list:
<div class="list-group">
<a class="list-group-item" ng-repeat="job in jobs" ui-sref="jobs.detail({ JobId: job.JobId })">
<dl>
<dt>{{job.Name}}</dt>
<dd>{{job.Location}}</dd>
</dl>
Some insight on how to get this to work would be awesome.
Thank You-
If I have inferred your goal correctly, you're issue is on the following line:
$scope.job = utils.findById($scope.jobs, $stateParams.JobId);
$scope.jobs will not exist like you expect it to. The jobs object was created in the list view's controller's scope, not the details view's controller. You'll want to do something like you have in the '' controller
JobService.getJobById($stateParams.JobId).then(function(data) {
$scope.job = data;
});

Categories

Resources