How to add previous/next options using angularjs or javascript? - javascript

How can I add previous/next buttons/options/links in my example so that I can move forward and backward steps after clicking on those options as per requirement in my third tab for the given content using angularjs or javascript or jquery. I have created fiddle

Are you looking for such behavior:
http://jsfiddle.net/6qm7jeo3/5/
I have added a prev and next function. Please have a look at it.
angular.module('TabsApp', [])
.controller('TabsCtrl', ['$scope', '$location', function($scope, $location) {
$scope.tabs = [{
title: 'One',
url: 'one.tpl.html'
}, {
title: 'Two',
url: 'two.tpl.html'
}, {
title: 'Three',
url: 'three.tpl.html'
}];
$scope.currentTab = 'one.tpl.html';
$scope.onClickTab = function(tab) {
$scope.currentTab = tab.url;
}
$scope.isActiveTab = function(tabUrl) {
return tabUrl == $scope.currentTab;
}
$scope.tab3 = 0;
$scope.next = function() {
$scope.tab3 = $scope.tab3 + 1;
}
$scope.prev = function() {
$scope.tab3 = $scope.tab3 - 1;
}
}]);

Here is the updated fiddle
<ul>
<li class="navBack" ng-click="navBack()"></li>
<li ng-repeat="tab in tabs" ng-class="{active:isActiveTab(tab.url)}" ng-click="onClickTab(tab)">{{tab.title}}</li>
<li class="navNext" ng-click="navNext()"></li>
</ul>
In Controller:
$scope.index = 0;
$scope.navBack = function(tab) {
if($scope.index > 0)
{
$scope.index--;
}
$scope.currentTab = $scope.tabs[$scope.index].url;
}
$scope.navNext = function() {
if( $scope.index < ($scope.tabs.length-1))
{
$scope.index++;
}
$scope.currentTab = $scope.tabs[$scope.index].url;
}

Related

Trying to activate a checkbox from a controller that lives in another controller

I am trying to activate a checkbox from a controller that lives in another controller. For example, I have a card named information technology under a separate controller and when I click this I want it to route to another page that has a checkbox for information technology from another controller and I want it checked as it renders the page.
The application architecture is very lengthy so I wont include any code base here. But I would like to know an approach I can take.
This is the controller where I want the logic to live and to mark a text box as checked (which lives on another controller).
angular
.controller("mycontroller", mycontroller);
mycontroller.$inject = [
"$scope"
];
// getting the getData() data
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
Below: Is the controller where the checkbox controller lives
angular
.controller('supplierIntelligenceCtrl', function ($scope, $q, FetchData, dataStore, SharedService,
$document, $window, $state, $rootScope, $timeout, DataCache,
$filter, $interval, $localStorage, $http) {
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
$scope.apply = function (type) {
$scope.select = false;
$scope.bigres = 0;
$scope.mobFil = 3;
$scope.applyFilter(type);
}
$scope.disableApply = false;
$scope.disableApply2 = false;
$scope.applyFilter = function (type) {
console.log("this is type ", type)
if (type == 'industries') {
$scope.filters.industries = $scope.industries.filter(function (e) {
console.log("this is e ", e.checked)
return e.checked;
}).map(function (f) {
console.log(" this is f >>>> ",
f)
return f.id
})
$scope.filters.countries = [];
if ($scope.countries != undefined) {
$scope.countries = $scope.countries.map(function (e) {
e.checked = false;
return e;
})
}
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.industries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCountriesByIndustries('industries=' + $scope.filters.industries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.countries = res.data;
$scope.countriesPage += 10
}, function () {
$scope.disableApply2 = false;
});
} else {
$scope.callBackend();
}
}
if (type == 'countries') {
$scope.filters.countries = $scope.countries.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id;
})
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.countries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCitiesByIndustriesAndCountries('industries=' + $scope.filters.industries + '&countries=' + $scope.filters.countries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.cities = res.data;
}, function () {
$scope.disableApply2 = false;
})
} else {
$scope.callBackend();
}
}
if (type == 'cities') {
$scope.filters.cities = $scope.cities.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id
})
$scope.start = 0;
$scope.callBackend();
}
if (type == 'classifications') {
$scope.filters.classifications = $scope.classifications.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.statusCode;
})
$scope.start = 0;
$scope.callBackend();
}
}
}
Here is the HTML where the checkbox lives:
<div ng-repeat="data in industries ">
<input id="{{data.id}}in" type="checkbox" aria-invalid="false"
ng-model="data.checked"
ng-change="getData(data,'industry')">
<label for="{{data.id}}in">{{data.name}}</label>
</div>
Maybe Im missing the point here and perhaps am overlooking something. Im new to angularjs and need to implement this capability to route a button/card to another page that checks a checkbox filter.
Please - any advise would be great . :)
Here is an example of controllers sharing an array via a shared service injected by the dependency injector. Check the checkbox in one controller and it shows in the other.
angular.module('app', []);
angular.module('app')
.factory('dataService', [function () {
return {
data: [
{ prop: '1', checked: false },
{ prop: '2', checked: false },
{ prop: '3', checked: false },
{ prop: '4', checked: false }
]
};
}]);
angular.module('app')
.controller('controller1', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller2', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller3', ['dataService', function (dataService) {
this.toggleAll = () => {
dataService.data.forEach(item => item.checked = !item.checked)
};
}]);
[ng-controller] { display: inline-block; margin-right: 30px; vertical-align: top; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="controller1 as ctrl">
<strong>Controller 1</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller2 as ctrl">
<strong>Controller 2</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller3 as ctrl">
<strong>Controller 3</strong>
<div>
<button ng-click="ctrl.toggleAll()">Toggle all</button>
</div>
</div>
</div>
Put industries as a property on a shared service that you inject into both of the controllers by the dependency injector. Then one controller can bind it to it's view and the other one can change the checked properties on them.
Since you are talking about redirection and then checking a check box, you can try either of below options
Send selection 'information technology' in query string to redirected page and check the check box
If you own a back end server then put the value in cookie and read it in your angular js app
Hope this helps.

ng-repeat doesn´t load after ng-click

i´ve got an problem with my ng-repeat.
After clicking ng-click, my ng-repeat doesn´t load, the page is empty. I´ve got an html file calls "food.html" in which i call the ng-click() further i´ve got an "food-snack.html" file which contains the ng-repeat and at least my "controller.js" where the function of ng-click is calling. I hope someone can help me. Im sorry for my confusing notation but it´s my first blog.
1.food-snack.html
<ion-content class="padding" >
<ion-refresher pulling-text="Refresh" on-refresh="refreshAll('snack')"></ion-refresher>
<ion-checkbox class = "item-checkbox-right checkbox-dark" ng-repeat="food in snacks">
<h2><b>{{food.food}} </b></h2>
<p>Preis: {{food.price}} {{food.currency}}</p>
</ion-checkbox>
</ion-content>
2.food.html
<ion-content class="padding">
<br><br><br><br><br><br><br>
<button class = "button button-block button-dark" ng-click = "getSnacks()" > Snacks </button>
<button class = "button button-block button-dark" ng-click = "getSandwich()" > Sandwich </button>
</ion-content>
3.controller.js
.controller('TablesCtrl', function($scope, $stateParams, $ionicPopup, $http, $state, $timeout, Foods) {
$scope.getSnacks = function(){
$state.go("tab.food-snack");
$http.get('http://xxxxxx/connect.php?getSnacks=1').then(function successCallback(response)
{
$scope.snacks = Foods.appendAll(response.data);
console.log(response);
}, function errorCallback(response) {
var confirmPopup = $ionicPopup.confirm({
title: 'Nicht erfolgreich',
cancelText: 'Nein',
okText: 'Ja',
okType: 'button-dark',
cancelType: 'button-positive'
});
});
};//END OF FUNCTION getSnacks()
$scope.getSandwich = function ()
{
$state.go("tab.food-sandwich");
$http.get('http://xxxxxx/connect.php?getSandwich=1').then(function successCallback(response)
{
$scope.sandwich = Foods.appendAll(response.data);
console.log(response);
}, function errorCallback(response) {
var confirmPopup = $ionicPopup.confirm({
title: 'Nicht erfolgreich',
cancelText: 'Nein',
okText: 'Ja',
okType: 'button-dark',
cancelType: 'button-positive'
});
});
}// END OF FUNCTION $scope.getSanwich()
4. app.js
.state('tab.foods', {
cache: false,
url: '/addTable/foods',
views: {
'tab-tables': {
templateUrl: 'templates/foods.html',
controller: 'TablesCtrl'
}
}
})
.state('tab.food-snack', {
cache: false,
url: '/addTable/foods/food-snack',
views: {
'tab-tables': {
templateUrl: 'templates/food-snack.html',
controller: 'TablesCtrl'
}
}
})
5.services.js
.factory('Foods', function() {
var foods = [];
return {
appendAll: function(array) {
for(var i = 0 ; i < array.length; i++)
{
foods.splice(array[i]);
}
for (var i = 0; i < array.length; i++)
{
foods.unshift(array[i]);
}
return foods;
},
getAll: function() {
return foods;
},
remove: function(food) {
foods.splice(foods.indexOf(food), 1);
},
removeAll: function(array) {
for( var i = 0 ; i < array.length; i++)
{
foods.splice(array[i]);
}
},
get: function(foodId) {
for (var i = 0; i < foods.length; i++) {
if (foods[i].id === parseInt(foodId)) {
return foods[i];
}
}
return null;
}
The controller you shared is the controller of the food. html I guess and it is adding the snack list to it's scope which is not the scope of snack.html. In the food controller just change the state and in the controller of snacks call the service to get the snacks.

How to do an ng-repeat that returns items of an array every 3 seconds

I want to be able to return items from an array using ng-repeat.
What I want is some animated effect, where each item is displayed 3 seconds after the previous item.
Here is an example ng-repeat that return results after 3 seconds delay.
http://jsfiddle.net/98rbe9hc/
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="phone in phones | filter:delay_filter">
<span>Name : {{phone.name}}</span>
</li>
</ul>
</div>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', function($scope, $timeout) {
var delayed = false;
$scope.phones = [
{ name: 'Motorola' },
{ name: 'Nokia' },
{ name: 'Ericsson' }
];
var delayInMilliseconds = 3000;
var doneWaiting = false;
$scope.delay_filter= function(item){
return doneWaiting;
};
$timeout(function() {
doneWaiting = true;
}, delayInMilliseconds);
});
But what I want is for each item in array to be displayed 3 seconds after the previous item.
HTML
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="phone in phones" ng-if="count >= $index">
<span>Name : {{phone.name}} {{count}} {{$index}}</span>
</li>
</ul>
</div>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope, $interval) {
var delayed = false;
$scope.phones = [
{ name: 'Motorola' },
{ name: 'Nokia' },
{ name: 'Ericsson' }
];
var delayInMilliseconds = 3000;
$scope.count = 0;
$scope.cunter = $interval(function() {
$scope.count+=1;
if($scope.count >= $scope.phones.length){
$interval.cancel($scope.cunter);
console.log('end')
}
}, delayInMilliseconds);
});
</script>
First, you should use an $interval so the filter repeats. Also, try adding a doneWaiting to each item so you check for that in your filter.
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', function($scope, $interval) {
var delayed = false;
$scope.phones = [
{ name: 'Motorola', doneWaiting: false },
{ name: 'Nokia', doneWaiting: false },
{ name: 'Samsung', doneWaiting: false },
{ name: 'Ericsson', doneWaiting: false }
];
var delayInMilliseconds = 1000;
$scope.delay_filter= function(item){
return item.doneWaiting;
};
$scope.waitingInterval=$interval(function() {
for (i = 0; i < $scope.phones.length; i++) {
if(!$scope.phones[i].doneWaiting){
$scope.phones[i].doneWaiting = true;
if(i==$scope.phones.length-1){
$interval.cancel($scope.waitingInterval);
}
break;
}
}
}, delayInMilliseconds);
});

angularjs restricting count to current scope

I am tring to setup a counter where for each country in my list I can keep count of how many clicks there has been plus an overall tally.
I have the below so far which can be viewd in this fiddle. The issue I am having is that I am not able to keep the count unique for each country. How can this be achieved?
<div ng-app="myApp">
<div data-ng-view></div>
</div>
'use strict';
var myApp = angular.module('myApp', ['ngRoute', 'templates/view1.html', 'templates/view2.html']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryListCtrl'
})
.when('/:id', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
})
}]);
myApp.factory('Countries', ['$q', function ($q) {
var countriesList = [];
// perform the ajax call (this is a mock)
var getCountriesList = function () {
// Mock return json
var contriesListMock = [
{
"id": "0",
"name": "portugal",
"abbrev": "pt"
}, {
"id": "1",
"name": "spain",
"abbrev": "esp"
}, {
"id": "2",
"name": "angola",
"abbrev": "an"
}
];
var deferred = $q.defer();
if (countriesList.length == 0) {
setTimeout(function () {
deferred.resolve(contriesListMock, 200, '');
countriesList = contriesListMock;
}, 1000);
} else {
deferred.resolve(countriesList, 200, '');
}
return deferred.promise;
}
var getCountry = function(id) {
var deferred = $q.defer();
if (countriesList.length == 0) {
getCountriesList().then(
function() {
deferred.resolve(countriesList[id], 200, '');
},
function() {
deferred.reject('failed to load countries', 400, '');
}
);
} else {
deferred.resolve(countriesList[id], 200, '');
}
return deferred.promise;
}
var cnt = 0;
var cntryCnt = 0;
var incCount = function() {
cnt++;
return cnt;
}
var incCntryCount = function(id) {
cntryCnt++;
return cntryCnt;
}
return {
getList: getCountriesList,
getCountry: getCountry,
getCount : function () {
return cnt;
},
getCntryCount : function () {
return cntryCnt;
},
incCount: incCount,
incCntryCount: incCntryCount
};
}]);
myApp.controller('CountryListCtrl', ['$scope', 'Countries', function ($scope, Countries) {
$scope.title = '';
$scope.countries = [];
$scope.status = '';
Countries.getList().then(
function (data, status, headers) { //success
$scope.countries = data;
},
function (data, status, headers) { //error
$scope.status = 'Unable to load data:';
}
);
}]);
myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries', function ($scope, $routeParams, Countries) {
$scope.country = {
id: '',
name: '',
abbrev: ''
};
var id = $routeParams.id;
Countries.getCountry(id).then(
function(data, status, hd) {
console.log(data);
$scope.country = data;
$scope.countOverall = Countries.getCount;
$scope.countCntry = Countries.getCntryCount;
$scope.clickCnt = function () {
$scope.countTotal = Countries.incCount();
$scope.country.clicks = Countries.incCntryCount(id);
console.log($scope);
};
},
function(data, status, hd) {
console.log(data);
}
);
}]);
angular.module('templates/view1.html', []).run(["$templateCache", function ($templateCache) {
var tpl = '<h1>{{ title }}</h1><ul><li ng-repeat="country in countries"><a href="#{{country.id}}">{{country.name}}</div></li></ul>';
$templateCache.put('templates/view1.html', tpl);
}]);
angular.module('templates/view2.html', []).run(["$templateCache", function ($templateCache) {
var tpl = '<div>{{country.name}} clicks {{countCntry()}} <br> overall clicks {{countOverall()}}</div><button>BACK</button><button ng-click="clickCnt()" >count clicks ++ </button>';
$templateCache.put('templates/view2.html', tpl);
}]);
The problem is that you are not incrementing a count based on the country. Working on the fiddle right now.
EDIT:
I've updated the fiddle: http://jsfiddle.net/1xtc0zhu/2/
What I basically did was making the cntryCnt an object literal which takes the country id as a property and keeps the right counting per each id, like so:'
var cnt = 0;
var cntryCnt = {};
...
// The function now receives the country id and increments the specific country clicks only.
var incCntryCount = function(id) {
cntryCnt[id] = cntryCnt[id] || 0;
cntryCnt[id]++;
return cntryCnt[id];
}
The rest of the changes are in the templates, and are basically only sending the country id as a param when getting or incrementing the counts.
Also, this is not an Angular Specific question, but more a programming in general question.

AngularsJS list and edit with 2 controllers

I try to do my first angularjs application, but i have a problem. I have 2 controllers (and i would like to keep 2): the first to list items, the second to edit or create an item.
When I save an item, or create a new item, i can't edit another or create another, after to do one action the form can't load or save... The problem seems to be this line :
$scope.editPlace = {};
But I don't understand why...
DEMO :
http://jsfiddle.net/cxL7qmke/
HTML:
<div ng-app="mapApp">
<div ng-controller="EditPlaceCtrl">
<form name="editPlaceForm">
<fieldset>
<label for="title">Title:</label>
<input id="title" type="text" ng-model="editPlace.title">
<input type="hidden" ng-model="editPlace.id" />
<button type="submit" ng-click="savePlace()">Save</button>
</fieldset>
</form>
</div>
<section ng-controller="PlaceCtrl">
<ul>
<li ng-repeat="place in places">
<label>{{place.title}} edit</label>
</li>
</ul>
</section>
</div>
JS :
var mapApp = angular.module('mapApp', []);
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
$rootScope.editPlace = angular.copy(placeService.get(id));
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.savePlace = function () {
placeService.save($scope.editPlace);
$scope.editPlace = {};
}
});
mapApp.service('placeService', function ($filter) {
var uid = 3;
var places = [
{ id: 1, title: 'Item1', lat: 43.123, lng: -89.123 },
{ id: 2, title: 'Item2', lat: 43.321, lng: -89.321 }
];
this.getAll = function () {
return places;
}
this.get = function (id) {
var place, i;
for (i in places) {
if (places[i].id === id) {
return places[i];
}
}
return false;
};
this.save = function (place) {
if (place.id == null) {
place.id = this.uid++;
places.push(place);
} else {
for (i in places) {
if (places[i].id == place.id) {
places[i] = place;
}
}
}
};
});
I've made few changes and seems to work for me please see here
http://jsfiddle.net/m9bevovy/
in your service I've added
this.newPlace = {};
this.setNew = function (id) {
this.newPlace = this.get(id);
};
and your controllers :
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
placeService.setNew(id);
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.placeService = placeService;
$scope.savePlace = function () {
placeService.save($scope.placeService.newPlace);
$scope.placeService.newPlace = {};
}
});
You are using both $scope and $rootScope to hold the reference to editPlace.
If you want to use the $rootScope, use this in your savePlace function:
$rootScope.editPlace = {};
Instead of:
$scope.editPlace = {};
Here`s the working fiddle

Categories

Resources