i'm experimenting with ionic (and building using phonegap online builder) and i'm trying to add a factory now but it messes up and gives a blank white screen. i tried the fix in a similar problem : How to use factories with Ionic/Angular JS with phonegap?
but it still doesnt work. my services.js file looks like this:
.factory('userFactory', [function() {
var users = [
{name: 'Omar', city: 'rizal'},
{name: 'Ganny', city: 'makati'},
{name: 'Chester', city: 'manila'}
];
return {
getUsers: function(){
return users;
},
getUser: function(id){
for(i=0;i<users.length;i++){
if(users[i].name == id)
{
return users[i];
}
}
return null;
}
};
}])
and my controller looks like this:
angular.module('app.controllers', [])
.controller('CityCtrl', ['$scope', '$stateParams', '$location'
function ($scope, $stateParams, $location, userFactory) {
$scope.userdata = {};
$scope.enterCity = function(usern,city) {
if(userFactory.getUser(usern) != null)
{
$location.path('/page14');
}
else
{
alert('Failed');
}
}
}])
Your depdencenies to the controller is not properly formated,It should be
.controller('CityCtrl', ['$scope', '$stateParams', '$location','userFactory',
function ($scope, $stateParams, $location, userFactory) {
Related
Im using gulp-concat to merge all angular js files into one but after running gulp task i get this error in chrome console on runing application :
angular.js:13708Error: [ng:areq] http://errors.angularjs.org/1.5.7/ng/areq?p0=userboxController&p1=not%20a%20function%2C%20got%20undefined
my gulp task :
gulp.task('scripts', function () {
return gulp.src(['js/app/*.js', 'components/*/*/*.js'])
.pipe(concat('appscript.js'))
.pipe(minify())
.pipe(gulp.dest('./dist/js/'));
});
and gulp-concat merges dedicated angular js files into appscript.js like:
angular.module('app',[]);
angular
.module("app", [])
.controller("paymentCtrl", ['$scope', '$http', function ($scope, $http) {
$http.get('data/payments.json').then(function (payments) {
$scope.payments = payments.data;
});
$scope.saveEntity = function () {
console.info("goog");
}
}]);
angular
.module("app",[])
.controller("userboxController", ['$scope', '$http',function ($scope, $http, usersService) {
usersService.getCurrentUser().then(function (user) {
$scope.user = user.data;
});
}]);
angular
.module("app",[])
.controller("usersController",['$scope', '$http','usersService', function ($scope, $http, usersService) {
usersService.getAll().then(function (users) {
$scope.users = users.data;
});
}]);
angular
.module("app", [])
.directive('usersGrid', function () {
return {
templateUrl : 'components/users/template/grid.html'
}
});
what's wrong with angular?!!
This is not a merge related problem.
You are making app modules every time with
angular.module('app', [])
You have to initialise module only one place and you will be using same module every time with ~ [] brackets.
Please find the plunker here
var myApp = angular.module('app');
myApp.controller("paymentCtrl", ['$scope', '$http', function($scope, $http) {
$http.get('data/payments.json').then(function(payments) {
$scope.payments = payments.data;
});
$scope.saveEntity = function() {
console.info("goog");
}
}]);
myApp.controller("userboxController", ['$scope', '$http', function($scope, $http, usersService) {
$scope.user = 'abc';
}]);
myApp.controller("usersController", ['$scope', '$http', 'usersService', function($scope, $http, usersService) {
usersService.getAll().then(function(users) {
$scope.users = users.data;
});
}]);
myApp.directive('usersGrid', function() {
return {
templateUrl: 'components/users/template/grid.html'
}
});
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;
});
I'm trying to return true or false from Laravel to a $scope directive in Angularjs. This is the laravel code that is called:
public function check() {
return Response::json(Auth::check());
}
This is the service that queries Laravel:
app.factory('UserService', ['$http', '$location', function($http, $location) {
return {
loggedIn: function() {
var c = $http.get('/auth/check');
c.success(function(data) {
console.log(data);
return data;
});
}
}
}]);
The response logs fine in the console, but I cant seem to bind it to a $scope directive:
app.controller('BaseController', ['$scope', 'UserService', function($scope, UserService) {
$scope.loggedIn = UserService.loggedIn();
}]);
Returns nothing when I call it as:
{{ loggedIn }}
...in my view.
Any help?
The $http service returns a promise. So you would have to write something like
app.factory('UserService', ['$http', '$location', function($http, $location) {
return {
loggedIn: function() {
return $http.get('/auth/check');
}
}
}]);
Controller:
UserService.loggedIn().success(function(data) {
$scope.loggedIn = data;
});
I'm creating an application with Angular.js and I'm getting a bit confused of how to use Angular to make it.
Below, you can see a preview of what I have for the moment, it's ugly but it works.
I just feel like there is much better ways of doing this, and would like to get other user inputs, knowing this :
The application will:
1) collect inputs over 8 steps
2) dependeing of those inputs, display specific results.
3) Being able to go to any state at any moment
// Create an application module
var app = angular.module('website', ['ngSanitize','ngAnimate','ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "js/partials/home.html",
controller: HomeCtrl
})
.state('step1', {
url: "/step1",
templateUrl: "js/partials/step1.html",
controller: Step1Ctrl
})
.state('step2', {
url: "/step2",
templateUrl: "js/partials/step2.html",
controller: Step2Ctrl
})
.state('step3', {
url: "/step3",
templateUrl: "js/partials/step3.html",
controller: Step3Ctrl
})
.state('step4', {
url: "/step4",
templateUrl: "js/partials/step4.html",
controller: Step4Ctrl
})
.state('step5', {
url: "/step5",
templateUrl: "js/partials/step5.html",
controller: Step5Ctrl
})
.state('step6', {
url: "/step6",
templateUrl: "js/partials/step6.html",
controller: Step6Ctrl
});
});
function getNewPercentageValue(step,percent){
var NewPercentage = 0;
if(percent){
NewPercentage = percent * step;
}else{
$rootScope.values.ActualPercentage = (100/8);
NewPercentage = $rootScope.values.ActualPercentage * step;
}
return NewPercentage;
}
function HomeCtrl($scope, $http, $rootScope, $state) {
/* DEFAULT VARIABLES */
$rootScope.values = {
ActualPercentageSteps: (100/8),
ActualPercentage: 0
};
}
function Step1Ctrl($scope, $http, $rootScope, $state) {
$rootScope.values.ActualPercentage = getNewPercentageValue(1,$rootScope.values.ActualPercentageSteps);
$scope.services = [
{name: 'Service 1', id: 1},
{name: 'Service 2', id: 2},
{name: 'Service 3', id: 3},
{name: 'Service 4', id: 4},
];
$scope.FormCtrlAddService = function(service){
};
$scope.FormCtrlRemoveService = function(service){
};
}
function Step2Ctrl($scope, $http, $rootScope, $state) {
/*
STEP 2
*/
$rootScope.values.ActualPercentage = getNewPercentageValue(2,$rootScope.values.ActualPercentageSteps);
$scope.FormCtrlAddKeyword = function(keyword){
};
$scope.FormCtrlRemoveKeyword = function(keyword){
};
$scope.updateValue = function(value){
};
}
function Step3Ctrl($scope, $http, $rootScope, $state) {
/*
STEP 3
*/
$rootScope.values.ActualPercentage = getNewPercentageValue(3,$rootScope.values.ActualPercentageSteps);
}
function Step4Ctrl($scope, $http, $rootScope, $state) {
/*
STEP 4
*/
$rootScope.values.ActualPercentage = getNewPercentageValue(4,$rootScope.values.ActualPercentageSteps);
}
function Step5Ctrl($scope, $http, $rootScope, $state) {
}
function Step6Ctrl($scope, $http, $rootScope, $state) {
}
function Step7Ctrl($scope, $http, $rootScope, $state) {
}
You can define your controllers using app.controller("MyCtrl", function($scope){}) and then don't need to have all the globally defined functions (just reference them using a quoted string like controller:"MyCtrl").
Aside from that you can move your common data into a service or factory since both end up being singletons and will persist the data throughout the lifetime of the application, here's a plunk showing an example:
http://plnkr.co/edit/4OYWi35Ke2GGDB6wY2W9
main thing to note here is use of angular.copy when attempting to replace the entire object instead of just using = since both controllers are just pointing to the same referenced object so I don't ever want to create a new object and point the service at that or things would get disconnected.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Service) {
$scope.items = Service.items;
$scope.someModel = {};
$scope.addItem = function(item){
Service.addItem(item);
}
$scope.resetItems = function(){
Service.resetItems();
}
});
app.controller('AnotherCtrl', function($scope, Service) {
$scope.items = Service.items;
});
app.service('Service', function($timeout){
var someService = {
items:[],
id:0,
addItem:function(item){
someService.items.push({label:item, id:someService.id++});
},
resetItems:function(){
someService.id=0;
//simulated HTTP call
$timeout(function(){
angular.copy([], someService.items);
})
}
};
return someService;
})
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 ?