i have a problem that i want to local storage a list and load it but
i found two problems that removing the item does not work well
and local storage is not working
.controller('tasksCtrl', [
'$scope',
'$stateParams',
'$localStorage',
function($scope, $stateParams) {
var dirlist = this;
var tasks = [
{
name: 'add task',
time: '12',
type: 'test'
}, {
name: 'do the home work',
time: '11',
type: 'study'
}
];
dirlist.list = tasks;
dirlist.toggle = false;
dirlist.addtask = function() {
dirlist.list.push({name: dirlist.name, time: dirlist.time, type: dirlist.type});
dirlist.name = '';
dirlist.time = '';
};
dirlist.remove = function(item) {
dirllist.splice(dirlist.list.indexOf(item), 1)
};
dirlist.saveData = function() {
$localStorage.list = tasks;
}
dirlist.loadData = function() {
dirlist.list = $localStorage.list;
}
}
])
local storage is not working
This is because you haven't passed the dependency in your controller.
You are passing only scope and stateParams.
Here's how you can fix it,
.controller('tasksCtrl', [
'$scope',
'$stateParams',
'$localStorage',
function($scope, $stateParams, $localStorage) {
Now, $localStorage can be used as localStorage service.
Hope it helps.
Cheers coding!
Related
I'm trying to use the confirm function of an angular material $mdDialog to clear an array and then log this array to the console, but there seems to be an issue with accessing 'this' objects/arrays/expressions/functions within the $mdDialog function itself, with the console saying that whatever item references is undefined, even if used previously in other controller functions.
Does the $mdDialog directive have an issue with controllerAs syntax?
-
Controller:
app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout) {
this.selectedNotification = null;
this.notifications = [
{
title: 'Notification One',
description: 'Description...',
time: '2017-10-27T16:39:32+00:00',
importance: 'Low',
read: false
},
etc...
$scope.clearNotifications = function(ev) {
var confirm = $mdDialog.confirm()
.parent(angular.element('body'))
.clickOutsideToClose(true)
.title('Are you sure you want to clear all notifications?')
.textContent('This action cannot be undone.')
.ariaLabel('Confirm notifications list clearance')
.ok('Yes')
.cancel('No')
.targetEvent(ev)
$mdDialog.show(confirm).then(function() {
$scope.status = 'All notifications deleted';
console.log($scope.status);
this.notifications.length = 0;
console.log(this.notifications);
}, function() {
$scope.status = 'Notifications list not cleared';
console.log($scope.status);
})
}
The this in:
$mdDialog.show(confirm).then(function() {
...
this.notifications.length = 0; // <---- here
...
}, function() {
...
})
refers to the promise resolve function of the promise returned by $mdDialog.show(), if you wanted to access the controller's notifications member you'd have to create a var that refers to the controller's this:
app.controller('notificationsController', function($scope, $state,
$http, $document, $mdDialog, $filter, $timeout) {
var _this = this; // <--- Now _this is the controller
this.notifications = [
{
title: 'Notification One',
description: 'Description...',
time: '2017-10-27T16:39:32+00:00',
importance: 'Low',
read: false
},
etc...
$scope.clearNotifications = function(ev) {
...
$mdDialog.show(confirm).then(function() {
...
_this.notifications.length = 0; //<--- using _this and not this
...
}, function() {
...
})
}
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) {
I am running into an asynchronous issue with my stats controller. I have a controller that queries the db and returns the objects. In this controller I use the filter to get the ones with the platform Facebook and I put this into $rootScope.facebookObjects.
First controller:
app.controller('statsCtrl', function ($scope, $log, $http, $timeout, $filter, Data, $rootScope) {
Data.get('stats').then(function(data){
$scope.stats = data.data;
$scope.currentPage = 1; //current page
$scope.filteredItems = $scope.stats.length; //Initially for no filter
$scope.totalItems = $scope.stats.length;
$scope.list_pages = [
{
id: '5',
name: '5'
}, {
id: '10',
name: '10'
}, {
id: '20',
name: '20'
}, {
id: '50',
name: '50'
}, {
id: '100',
name: '100'
}
];
$scope.maxSize = 5;
$rootScope.facebookObjects = $filter('filter')($scope.stats, { platform: "facebook" });
$rootScope.twitterObjects = $filter('filter')($scope.stats, { platform: "twitter" });
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
I have a second controller that uses the $rootScope.facebookObjects to populate the chart. The problem is I need to wait until the $rootScope.facebookObjects has a value. Currently my console log shows undefined. I am looking into promises but I am a little unsure which controller to use it in and how to properly use it.
Second Controller:
app.controller("PieCtrl", function ($scope, $rootScope, $timeout, $log) {
$log.log('facebook - '+$rootScope.facebookObjects.length);
});
$rootScope.$watch('facebookObjects', function(newValue, oldValue) {
//do your job
});
while you could use $watch to watch it, but i'm not sure it's a good way to share data between the controllers, and even more data is acync.
I have created an example for you with angular factory:
HTML:
<div ng-app="jsfiddle">
<div ng-controller="MainCtrl">
Data: {{data}}<br>
</div>
<div ng-controller="SecondCtrl">
Data: {{data}}<br>
</div>
</div>
Angular:
var app = angular.module('jsfiddle', []);
app.factory('myService', function($http) {
return {
async: function() {
return $http.get('https://api.myjson.com/bins/1v21f');
}
};
});
app.controller('MainCtrl', function( myService,$rootScope, $scope, $timeout) {
$scope.data = "oron";
myService.async().then(function(d) {
$timeout(function() {
$rootScope.data = d;
}, 1000);
});
});
app.controller('SecondCtrl', function($rootScope, $scope, $timeout) {
$scope.test = $rootScope.data;
});
MainCtrl is calling myService and store the response on the $rootScope.
then the when the value is ready it will update the data object on the SecondCtrl.
Thank you everyone for your help. Here is what I came up with based off of your answers.
First Controller:
$scope.facebookObjects = $filter('filter')($scope.stats, { platform: "facebook" });
$scope.twitterObjects = $filter('filter')($scope.stats, { platform: "twitter" });
$scope.$broadcast('update_chart_controller', {
fb: $scope.facebookObjects,
tw: $scope.twitterObjects
});
Second Controller:
$scope.$on("update_chart_controller", function(event, args) {
$scope.data = [args.fb.length, args.tw.length];
});
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 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;
})