I'm trying to apply some sort of filter to my code but it's not changing anything when i click on the menu. I need to show all my albums initially and if the user clicks in one of te artists i want to filter them. Down here is my controller:
Function ListCtrl($scope, $http) {
$http({
method: 'GET',
url: 'json/json_price_1.json'
}).success(function(data) {
$scope.artists = data.artists; // response data
$scope.albums = [];
$scope.currentArtist = null;
$scope.setArtist = function(name) {
$scope.currentArtist = $scope.artists[name];
};
if ($scope.currentArtist == null) {
angular.forEach($scope.artists, function(element, index) {
angular.forEach(element.albums, function(album, index) {
$scope.albums.push(album);
});
});
} else {
angular.forEach($scope.currentArtist.albums, function(album, index) {
$scope.albums.push(album);
});
};
});};
My html is the following:
<div ng-controller="ListCtrl">
<ul class="topcoat-list" ng-repeat="artist in artists">
<li class="topcoat-list__item">
<a href="" ng-click="setArtist(artist.name)">
{{artist.name}}
</a>
</li>
</ul></div>
<div ng-controller="ListCtrl">
<ul ng-repeat="album in albums">
<li>{{album.title}}</li>
</ul>
Thanks for your time guys!
Not an expert in angularjs, the problem is you are not filtering the albums after the artist is set.
Function ListCtrl($scope, $http) {
$scope.setArtist = function (name) {
$scope.currentArtist = $scope.artists[name];
$scope.filter();
};
$scope.filter = function () {
$scope.albums = [];
if (!$scope.currentArtist) {
angular.forEach($scope.artists, function (element, index) {
angular.forEach(element.albums, function (album, index) {
$scope.albums.push(album);
});
});
} else {
angular.forEach($scope.currentArtist.albums, function (album, index) {
$scope.albums.push(album);
});
};
}
$http({
method: 'GET',
url: 'json/json_price_1.json'
}).success(function (data) {
$scope.artists = data.artists; // response data
$scope.currentArtist = undefined;
$scope.filter()
});
};
The angular solution will be is to use an filter - something like this demo
Related
I am trying to pass data through <select multiple> from HTML to my RESTful.
That data is an array of String. I don't know why when it comes to my backend it's empty.
This is my REST:
#PutMapping("/events")
#Timed
public ResponseEntity<Event> updateEvent(#RequestBody Event event, #ModelAttribute("attendeesToParse") ArrayList<String> attendeesToParse) throws URISyntaxException {
//Some code
}
This is my HTML:
<div class="form-group">
<label>Attendees</label>
<select class="form-control" multiple name="attendeesToParse" ng-model="vm.usernames"
ng-options="customUser as customUser.username for customUser in vm.customusers">
<option value=""></option>
</select>
</div>
I tried to fix this one for days, I googled it so much but I found no solutions. Please help me.
I can not change my HTML into a JSP due to my project's structure and business logic.
Why does it come empty? If I try to show some logs I see an empty array [].
UPDATE
My HTML form call:
<form name="editForm" role="form" novalidate ng-submit="vm.save()">
<!-- some code -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
<span class="glyphicon glyphicon-ban-circle"></span> <span data-translate="entity.action.cancel">Cancel</span>
</button>
<button type="submit" ng-disabled="editForm.$invalid || vm.isSaving" class="btn btn-primary">
<span class="glyphicon glyphicon-save"></span> <span data-translate="entity.action.save">Save</span>
</button>
</div>
</form>
My event-dialog-controller.js: (is the .js controller that works with form)
(function() {
'use strict';
angular
.module('businessRequestApp')
.controller('EventDialogController', EventDialogController);
EventDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Event', 'Desk', 'CustomUser'];
function EventDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, entity, Event, Desk, CustomUser) {
var vm = this;
vm.event = entity;
vm.clear = clear;
vm.datePickerOpenStatus = {};
vm.openCalendar = openCalendar;
vm.save = save;
vm.reftables = Desk.query({filter: 'event-is-null'});
$q.all([vm.event.$promise, vm.reftables.$promise]).then(function() {
if (!vm.event.refTable || !vm.event.refTable.id) {
return $q.reject();
}
return Desk.get({id : vm.event.refTable.id}).$promise;
}).then(function(refTable) {
vm.reftables.push(refTable);
});
vm.customusers = CustomUser.query();
$timeout(function (){
angular.element('.form-group:eq(1)>input').focus();
});
function clear () {
$uibModalInstance.dismiss('cancel');
}
function save () {
vm.isSaving = true;
if (vm.event.id !== null) {
Event.update(vm.event, onSaveSuccess, onSaveError);
} else {
Event.save(vm.event, onSaveSuccess, onSaveError);
}
}
function onSaveSuccess (result) {
$scope.$emit('businessRequestApp:eventUpdate', result);
$uibModalInstance.close(result);
vm.isSaving = false;
}
function onSaveError () {
vm.isSaving = false;
}
vm.datePickerOpenStatus.date = false;
function openCalendar (date) {
vm.datePickerOpenStatus[date] = true;
}
}
})();
My event-service.js:
(function() {
'use strict';
angular
.module('businessRequestApp')
.factory('Event', Event);
Event.$inject = ['$resource', 'DateUtils'];
function Event ($resource, DateUtils) {
var resourceUrl = 'api/events/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.date = DateUtils.convertLocalDateFromServer(data.date);
}
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
}
});
}
})();
My event.controller.js:
(function () {
'use strict';
angular
.module('businessRequestApp')
.controller('EventController', EventController);
EventController.$inject = ['Event', 'CustomUser', '$scope'];
function EventController(Event, CustomUser, $scope) {
var vm = this;
vm.events = [];
vm.customUsers = [];
vm.usernames = ["test1", "test2", "test3"];
$scope.allCustomUsers = [];
loadAll();
function loadAll() {
Event.query(function (result) {
vm.events = result;
vm.searchQuery = null;
});
CustomUser.query(function (result) {
vm.customUsers = result;
vm.searchQuery = null;
for (var i = 0; i < vm.customUsers.length; i++) {
$scope.allCustomUsers.push(vm.customUsers[i].username);
}
});
}
}
})();
If you're using angularJS, you can't data bind data with #ModelAttribute, because #ModelAttribute exists only with template engines such as JSP, and AngularJS is not a template engine within Spring. Try instead to use #RequestBody on String parameter, and then extract the data using Jackson.
One more issue, How exactly do you pass your values from front to back? I don't see any $http angularJS call, and no HTML form with POST method.
I'm developing a simple CRUD application with MEAN stack. So the scenario is a user post a data to the server and it will render the data in real-time. Everything works fine but whenever I refresh the page ,
It will sort of loads all the content, every time it tries to fetch the data. I guess this is a caching problem.
So what I want to achieve is, every time a user refresh the page or go to another link, the content will be there without waiting for split seconds.
Here's the link to test it on, try to refresh the page
https://user-testing2015.herokuapp.com/allStories
and the code
controller.js
// start our angular module and inject our dependecies
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function(Story, $routeParams, socketio) {
var vm = this;
vm.stories = [];
Story.all()
.success(function(data) {
vm.stories = data;
});
Story.getSingleStory($routeParams.story_id)
.success(function(data) {
vm.storyData = data;
});
vm.createStory = function() {
vm.message = '';
Story.create(vm.storyData)
.success(function(data) {
// clear the form
vm.storyData = {}
vm.message = data.message;
});
};
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
.controller('AllStoryController', function(Story, socketio) {
var vm = this;
Story.allStories()
.success(function(data) {
vm.stories = data;
});
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
service.js
angular.module('storyService', [])
.factory('Story', function($http, $window) {
// get all approach
var storyFactory = {};
var generateReq = function(method, url, data) {
var req = {
method: method,
url: url,
headers: {
'x-access-token': $window.localStorage.getItem('token')
},
cache: false
}
if(method === 'POST') {
req.data = data;
}
return req;
};
storyFactory.all = function() {
return $http(generateReq('GET', '/api/'));
};
storyFactory.create = function(storyData) {
return $http(generateReq('POST', '/api/', storyData));
};
storyFactory.getSingleStory = function(story_id) {
return $http(generateReq('GET', '/api/' + story_id));
};
storyFactory.allStories = function() {
return $http(generateReq('GET', '/api/all_stories'));
};
return storyFactory;
})
.factory('socketio', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
}
};
}]);
api.js (both find all object and single object)
apiRouter.get('/all_stories', function(req, res) {
Story.find({} , function(err, stories) {
if(err) {
res.send(err);
return;
}
res.json(stories);
});
});
apiRouter.get('/:story_id', function(req, res) {
Story.findById(req.params.story_id, function(err, story) {
if(err) {
res.send(err);
return;
}
res.json(story);
});
});
For api.js whenever I refresh the page for '/all_stories' or go to a '/:story_id' it will load the data for split seconds.
allStories.html
<div class="row">
<div class="col-md-3">
</div>
<!-- NewsFeed and creating a story -->
<div class="col-md-6">
<div class="row">
</div>
<div class="row">
<div class="panel panel-default widget" >
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>
<h3 class="panel-title">
Recent Stories</h3>
<span class="label label-info">
78</span>
</div>
<div class="panel-body" ng-repeat="each in story.stories | reverse" >
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-xs-10 col-md-11">
<div>
<div class="mic-info">
{{ each.createdAt | date:'MMM d, yyyy' }}
</div>
</div>
<div class="comment-text">
<h4>{{ each.content }}</h4>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3">
</div>
The loading problem you see is that the data is fetched after the view has been created. You can delay the loading of the view by using the resolve property of the route:
.when('/allStories', {
templateUrl : 'app/views/pages/allStories.html',
controller: 'AllStoryController',
controllerAs: 'story',
resolve: {
stories: function(Story) {
return Story.allStories();
}
}
})
Angular will delay the loading of the view until all resolve properties have been resolved. You then inject the property into the controller:
.controller('AllStoryController', function(socketio, stories) {
var vm = this;
vm.stories = stories.data;
});
I think you should use local storage. suited module - angular-local-storage
The data is kept aslong you or the client user clean the data,
Usage is easily:
bower install angular-local-storage --save
var storyService = angular.module('storyService', ['LocalStorageModule']);
In a controller:
storyService.controller('myCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {
localStorageService.set(key, val); //return boolean
localStorageService.get(key); // returl val
}]);
Match this usage to your scenario (for example - put the stories array on and just append updates to it)
app.controller('PageCtrl', ['$scope', '$stateParams', '$state', 'USER_ROLES', 'AuthService', function($scope,$stateParams,$state,USER_ROLES, AuthService){
//console.log("Page Controller reporting for duty.");
$scope.currentUser = null;
$scope.currentUserExists = false; //<- defined in scope of PageCtrl
$scope.userRoles = USER_ROLES;
$scope.isAuthorized = AuthService.isAuthorized;
$scope.setCurrentUser = function (user) {
$scope.currentUser = user;
$scope.currentUserExists = true; //<- set true here!!
};
Now in my html code I'm doing:
<body ng-app="myApp" ng-controller="PageCtrl">
....
<div class="navbar-brand" ng-if="currentUserExists">Welcome!!</div>
<div class="navbar-brand" ng-if="currentUser.data.teacher._id">Welcome2!!</div>
Iv tried ng-show, and I'm trying both examples above to test it.
If i log to console currentUser within my js file everything appears to be working normal. But nothing will show on my page.
Am i missing something??
currentUser is json set like:
$scope.login = function (credentials) {
AuthService.login(credentials).then(function (user) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.setCurrentUser(user);
console.log("currentuser");
console.log($scope.currentUser.data.teacher._id); //Yes its working...
}, function () {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
...
authService.login = function (credentials) {
return $http({
method: 'POST',
url: 'proxy2.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
url: 'http://teach.classdojo.com/api/dojoSession?_u=tid',
login: credentials.login,
password: credentials.password,
type: 'teacher'
}
}).success(function (res) {
alert("login success");
Session.create(res.teacher._id, "admin");
return res.teacher;
}).error(function (res) {
alert(res.error.detail);
});
};
You may want to try this:
<div class="navbar-brand" ng-if="currentUserExists==true">Welcome!!</div>
The problem may be due to your setting a primitive value on the scope.
Try using view.currentUserExists instead- so set $scope.view = {currentUserExists: false} in the initialization and then $scope.view.currentUserExists = true in the promise resolution.
I couldn't understand why the scope wasn't working on the page, apparently due to inheritence or maybe because i was using $scope in two controllers?
Anyway i solved it using a service:
$scope.login = function (credentials) {
AuthService.login(credentials).then(function (user) {
userService.setCurrentUser(user); //<----Added this
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
}, function () {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
...
var updateUser = function() {
scope.view.currentUser = userService.getCurrentUser();
};
scope.$on(AUTH_EVENTS.loginSuccess, updateUser);
..
app.service('userService', function() {
var currentUser = null;
return {
setCurrentUser: function(user) {
currentUser = user;
},
getCurrentUser: function() {
return currentUser;
}
};
});
I want to get the data for three get URIs. In the form, the user enters a date which is used to retrieve three different datas from different URIs using the date user has entered. How ever this does not work. Below is my current code that I have written, but it does not work.
In simple words, The user selects a date, which is passed onto the URI and data is retrieved from the API, this happens in three functions, I want all three functions to run when the user clicks fetch.
HTML:
<div style="text-align: center" type="text/ng-template" ng-controller="DailyCtrl" class="users">
<h1>{{message}}</h1>
<form style="text-align: center" name="myform" id="myform1" ng-submit="fetch()" >
<input type="date"
ng-model="date"
value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<div><center><button type="submit" >Fetch</button></center></div>
</form>
{{formdata.date}}
<ul ng-controller="NewCooliosCtrl" ng-repeat="newCoolio in newCoolios.newCoolios">
<li>{{newCoolio.personID}}, {{newCoolio.placeID}}, {{newCoolio.datePlaced}}</li>
</ul>
<ul ng-controller="NewPlacesCtrl" ng-repeat="newPlace in newPlaces.newPlaces">
<li>{{newPlace}} </li>
</ul>
<ul ng-controller="NewUsersCtrl" ng-repeat="newUser in newUsers.newUsers">
<li>New Users: {{newUser}} </li>
</ul></br></br>
</div>
Angularjs:
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getdailydata', {
templateUrl: 'templates/getnewcoolios.html',
controller: 'DailyCtrl'
})
}])
.controller('DailyCtrl', function ($scope) {
$scope.toFetch = [];
$scope.fetch = function () {
for (var i = 0; i < $scope.toFetch.length; i++) {
$scope.toFetch[i]();
}
}
})
.controller('NewUsersCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewusers?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newUsers = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New Users';
})
}
$scope.toFetch.push($scope.fetch);
})
.controller('NewPlacesCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewplaces?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newPlaces = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New places';
})
}
$scope.toFetch.push($scope.fetch);
})
.controller('NewCooliosCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewcoolios?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newCoolios = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New Coolios';
})
}
$scope.toFetch.push($scope.fetch);
})
That should be in a service really as charlietfl pointed out - but can you not simplify the whole thing down and do something along the lines of (pseudo code!!!) :
.controller('DailyCtrl', function ($scope, $filter, $http) {
$scope.newCoolios = [];
$scope.newPlaces = [];
$scope.newUsers = [];
$scope.date;
$scope.fetch = function(){
var parsedDate = 'date': $filter('date')(this.date, 'dd/MM/yyyy');
$http.get('http://94.125.132.253:8001/getnewusers?date=' + parsedData.date).success(function (data) {
$scope.newUsers = data;
});
$http.get('http://94.125.132.253:8001/getnewplaces?date=' + parsedData.date).success(function (data) {
$scope.newPlaces = data;
});
$http.get('http://94.125.132.253:8001/getnewusers?date=' + parsedData.date).success(function (data) {
$scope.newUsers = data;
});
}
});
The the html could be something like....
<div style="text-align: center" type="text/ng-template" ng-controller="DailyCtrl" class="users">
<h1>{{message}}</h1>
<input type="date" ng-model="date" value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<button ng-click="fetch()">Update</button>
<ul ng-repeat="newCoolio in newCoolios">
<li>{{newCoolio.personID}}, {{newCoolio.placeID}}, {{newCoolio.datePlaced}</li>
</ul>
<ul ng-repeat="newPlace in newPlaces">
<li>{{newPlace}} </li>
</ul>
<ul ng-repeat="newUser innewUsers">
<li>New Users: {{newUser}} </li>
</ul>
</div>
I'm pretty new to AngularJS, I want to pass the scope to a service so I can perform a tag search based on the scope.value.
<div data-ng-app="instaSearch" data-ng-controller="search">
<div>
<input type="text" value={{value}} data-ng-model='value'/>
</div>
<p data-ng-hide="value">type a tag</p>
<p data-ng-show="value">...looking for {{value}}</p>
<ul>
<li data-ng-repeat="r in results">
<a>
<img ng-src="{{r.images.thumbnail.url}}" alt="" />
</a>
</li>
</ul>
</div>
Here is the JS
var app = angular.module('instaSearch', ['ngResource']);
app.factory('instagram', function($resource){
return {
searchTag: function(callback){
var api = $resource('https://api.instagram.com/v1/tags/:tag/media/recent?client_id=:client_id&callback=JSON_CALLBACK',{
client_id: '3e65f044fc3542149bcb9710c7b9dc6c',
tag:'dog'
},{
fetch:{method:'JSONP'}
});
api.fetch(function(response){
callback(response.data);
});
}
}
});
app.controller('search', function($scope, instagram){
$scope.$watch('value', function(){
$scope.results = [];
instagram.searchTag(function(data){
$scope.results = data;
});
});
});
working example
You can access the value using $scope.value.
app.factory('instagram', function ($resource) {
return {
searchTag: function (tag, callback) {
var api = $resource('https://api.instagram.com/v1/tags/:tag/media/recent?client_id=:client_id&callback=JSON_CALLBACK', {
client_id: '3e65f044fc3542149bcb9710c7b9dc6c',
tag: tag
}, {
fetch: {
method: 'JSONP'
}
});
api.fetch(function (response) {
callback(response.data);
});
}
}
});
app.controller('search', function ($scope, instagram) {
$scope.$watch('value', function () {
$scope.results = [];
instagram.searchTag($scope.value, function (data) {
$scope.results = data;
});
});
});
Demo: http://codepen.io/anon/pen/GHbIl