Angular - Fill dropdown based on selection - javascript

HTML
<div class="col-xs-2 type-image" ng-repeat='group in groups'>
<a class="thumbnail" ng-click='selectItem(group)'>
<img src="<% group.image %>" class="img-responsive">
</a>
</div>
<div class="col-md-5 type-description" ng-bind-html="selectedItem.description | unsafe"></div>
<div class="col-md-6 no-gutter">
<select ng-options="gurte.id for gurte in group.gurte"></select>
</div>
app.js
app.controller('gurtController', function($scope, $http) {
$scope.groups = [];
$scope.loading = false;
$scope.init = function() {
$scope.loading = true;
$http.get('/api/groups').
success(function(data, status, headers, config) {
$scope.groups = data;
$scope.loading = false;
});
}
$scope.selectItem = function(item) {
$scope.selectedItem = item;
}
$scope.init();
});
How can I fill the select dropdown based on the selection in the upper block of the HTML? Am I right, that the scope is still on "group" when I have selected it in the top or do I have to pass "group" to the select field somehow?
If needed I can provide the output from the API too. basically its:
Group
-id
-name
-gurte (relationship) ->
- id
- spalten (many to many; ) ->
- id
- name (this needs to go to the dropdown)
-> pivot -> spalten_value

Related

How to get the indexpath or particular id from single list view cell on button click

I have list of items that i am displaying from db. So in each cell i have one button . So each cell have one seperate number ID .So when ever i press any cell button.That particular cell number id i need to get .Just to put one alert or console message to get that particular number ID. How to do that.
For example :
<ion-item ng-repeat="colls in Mycolls | filter: search | limitTo: listlength">
<div>
<img src="img/Reminder.png">
<span>Get number</span>
</div>
<div>
<img src="img/phone.png">
<span>GET NAME</span>
</div>
</ion-item>
This above code is my list view to populate my data, with each cell have one button.Please help me out how can i do that using ng-click.
Here my controller:
.controller('collectionsCtrl', function($scope, $state, $window, $ionicPopup, $stateParams, $ionicLoading, $timeout, $ionicHistory, collectionsfactory) {
$scope.GoBack = function() {
$state.go('menu.mydata');
};
$scope.mdID = "1";
$scope.orderInfo = {
mdID: $scope.mdID
};
$ionicLoading.show();
collectionsfactory.save($scope.orderInfo, function(response) {
if (response.status == 1) {
$ionicLoading.hide();
$scope.Mycolls = response.allcollections;
$window.localStorage.setItem("order", JSON.stringify($scope.Mycolls));
console.log($scope.Mycolls);
} else {
$ionicLoading.hide();
$ionicPopup.alert({
title: "Failed",
content: "<center>" + response.message + "</center>"
});
}
});
});
Add a ng-click to the span in the repeated element that call your functions:
<ion-item ng-repeat="colls in Mycolls" ng-click="getColls(colls)>
<span ng-click="getNumber(colls)">Get number</span>
<span ng-click="getName(colls)">Get name</span>
</ion-item>
Here are getNumber() and getName() functions in controller:
$scope.savedColls = {};
$scope.getNumber = function(colls) {
$scope.savedColls.number = colls.number;
}
$scope.getName = function(colls) {
$scope.savedColls.name = colls.name;
}
call a function by ng-click and pass the id
In html
<span ng-click="getName(colls.name)"></span>
<span ng-click="getNumber(colls.number)"></span>
Inside the controller
$scope.getName = function(name) {
console.log('cell name',name);
}
$scope.getNumber = function(number) {
console.log('cell number',number);
}

Use search bar to filter data in data table based on search string

I am trying to apply a filter in a data table from input received from a search bar. I have an input field in header of my application. On entering a value in that search bar, I need the page to get redirected to 'http://localhost:1001/#/employees' page and the filtering should be applied.
Header html:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner" ng-controller="getUserHeader">
<div class="container">
<form class="navbar-search pull-right" ng-submit="applySearch()">
<input id="input-search" class="search-query" name="mysearch" ng-model="mysearch" placeholder="Search">
</form>
</div>
</div>
</div>
</div>
Header controller :
myApp.controller('getUserHeader', ['$scope', 'commonServices', 'dataTable', '$rootScope', '$location', '$filter', function ($scope, commonServices, dataTable, $rootScope, $location, $filter) {
commonServices.getReservations().then(function (result) {
$scope.data = result.data;
$scope.applySearch = function () {
alert($scope.mysearch);
}
});
}]);
I want to pass the mysearch value to the filter on data table contained in the partial view 'http://localhost:1001/#/employees'. The HTML code and controller code of that page is,
HTML :
<div class="row">
<div class="span12">
<div class="widget widget-table action-table">
<div class="widget-header"> <i class="icon-th-list"></i>
<h3>Employee</h3>
</div>
<div class="widget-content table-container" ng-controller="getEmployeesController" >
<table ng-table="employeesList" show-filter="true" class="table table-striped table-bordered">
<tr ng-repeat="employee in $data">
<td data-title="'#'">
{{ (itemsPerPage * (pageNumber-1)) + $index+1 }}
</td>
<td data-title="'First Name'" sortable="'firstName'" filter="{ 'firstName': 'text' }">
{{employee.firstName}}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
The filtering works fine from within this page.
Controller :
myApp.controller('getEmployeesController', ['$scope', 'employeeServices', 'dataTable', '$window', '$timeout', '$filter', function ($scope, employeeServices, dataTable, $window, $timeout, $filter) {
employeeServices.getEmployees().then(function (result) {
$scope.data = result.data;
});
Data Table is configured in App.js file :
myApp.factory('dataTable', ['$filter', 'ngTableParams', function($filter, ngTableParams) {
var factoryDefinition = {
render: function($scope, config, componentId, data) {
if(!config) config ={};
var config = angular.extend({}, {page:1, count:10}, config)
$scope[componentId] = new ngTableParams(config, {
total: data.length, // length of data
getData: function ($defer, params) {
// organize filter as $filter understand it (graph object)
var filters = {};
angular.forEach(params.filter(), function (val, key) {
var filter = filters;
var parts = key.split('.');
for (var i = 0; i < parts.length; i++) {
if (i != parts.length - 1) {
filter[parts[i]] = {};
filter = filter[parts[i]];
}
else {
filter[parts[i]] = val;
}
}
});
// use build-in angular filter
var filteredData = params.filter() ?
$filter('filter')(data, filters) :
data;
var orderedData = params.sorting() ?
$filter('orderBy')(filteredData, params.orderBy()) :
data;
params.total(orderedData.length); // set total for recalc pagination
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
$scope.pageNumber = params.page();
$scope.itemsPerPage = params.count();
}
});
}
}
return factoryDefinition;
}
]);
So basically I have different controllers in both the header and in the partial view. I want to enter a string on search bar in header and on enter click, it should redirect to the partial view and apply the filter on the data table contained inside.
How am I supposed to achieve this? Sadly I was not able to create a plunker for this.
This is how the values are passed to App.js file while a filter is applied from within the partial view (https://i.imgsafe.org/595e6265b7.jpg). I added this so that you can see how the custom data table works.
Thanks in advance.

Loading data in details modal using AngularJS

I'm trying to load data into modal using AngularJS. I did the load the data into a list of "cards" and it works fine. But, to each card, I need to open a details modal and to load the rest of the data within it. Follow my code:
//Part of index.html
<body ng-controller="CardsController">
<div class="container">
<div class="cards" ng-repeat="card in cards">
<h3>{{card.user}}</h3>
<button type="button" name="play" title="play" ng-click="toggleModal(card)">Play</button>
</div>
</div>
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{card.user}}</h3> <-- here is my problem!
</my-modal>
// js/controllers/cards-controller.js
angular.module('angstudy').controller('CardsController', function($scope, $http){
$scope.cards = [];
$http.get('http://localhost:3000/api/persons')
.success(function(retorno){
console.log(retorno);
$scope.cards = retorno;
})
.error(function(erro) {
console.log(erro);
});
$scope.modalShown = false;
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
};
});
// js/directives/modal-dialog.js
angular.module('modalDialog', [])
.directive('myModal', function() {
var ddo = {};
ddo.restrict = "E";
ddo.transclude = true;
ddo.scope = {
user: '#user',
show: '='
};
ddo.link = function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
};
};
ddo.templateUrl = 'js/directives/modal-dialog.html';
return ddo;
});
// js/directives/modal-dialog.html (template for the directive)
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<div class='ng-modal-close' ng-click='hideModal()'>X</div>
<div class='ng-modal-dialog-content'></div>
</div>
</div>
// js/main.js
angular.module('angstudy', ['modalDialog']);
The cards are been displayed normally and the modal opens, but does not display the AE values within the modal (in this case, I'm just testing the value "user", but the json has more data). If I insert just a static value, it displays...
I would've done it by keeping the modal html in a separate file and using a separate controller and I would pass the data to the Modal controller with the resolve keyword.
But since you are using the same controller on both the templates. You can keep a separate variable called $scope.SelectedCard to achieve the functionality.
In your toggleModal method you can assign the card as:
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
$scope.selectedCard = card;
};
and in the modal you can change to:
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{selectedCard.user}}</h3> <-- problem solved
</my-modal>

AngularJS chart update

Probably easy but I cant understand this ... Problem is that the pie chart is not going to be show updated content from data at POST query.
Predefined content are shown on the page.
markup :
<div class="col-lg-6 col-sm-12" id="pie-chart" ng-controller="ChartCtrlS">
<div class="panel panel-default">
<div class="panel-heading">Label 23 </div>
<div class="panel-body">
<canvas id="pie" class="chart chart-pie chart-xs" data="pie2.data" labels="pie2.labels"></canvas>
</div>
</div>
</div>
And controller code :
angular.module('sbAdminApp')
.controller('ChartCtrlS', ['$scope','$http', function($scope, $http) {
$scope.pie2 = {
labels : ["TheOne", "TheOne Next"],
data : [1, 1]
};
<---- CODE CUT -->
}).success(function (data, status, headers, config) {
var slabels = [];
var array = [];
var sdata = [array];
for (var i =0; i < data.length; i++ ) {
var nom = data[i];
if (nom.seats > 0) {
slabels.push(nom.name);
sdata.push (nom.seats);
}
}
$scope.pie2.labels.push.apply(slabels);
$scope.pie2.data.push.apply(sdata);
$scope.vpresults = data;
}).error(function (data, status, headers, config) {
$scope.status = status;
});
};
}]);
Angulajs version is 1.2.16, angulajs-chart 0.5.3

append html to the div with AngularJS

How can i pass html through in AngularJS controller ?
Here is my list.html:
<div class="col-xs-3" ng-repeat="item in companyData">
<a ng-click="getPackageInfo({{item.iCompanyID}},'{{item.vCompanyName}}')" class="block panel padder-v bg-primary item">
<span class="text-white block">{{item.vCompanyName}}</span>
</a>
<div id="packagehtml"></div>
</div>
<div id="lp" class="col-md-12 listing-div hidden"></div>
in controller.js:
$scope.pData = [];
$scope.getPackageInfo = function(id,name) {
$scope.name = name;
var summery = SubscriptionoptioncompanylistFactory.getSummary(id);
document.getElementById("lp").classList.remove("hidden");
$('.packages-data').html('');
$('#loading').show();
SubscriptionoptioncompanylistFactory.getPackageInDetail(id).
success(function(data) {
if(data != 0) {
$("#lp").html(summery); // this is used to append the data
document.getElementById("np").classList.add("hidden");
Array.prototype.push.apply($scope.pData, data);
$('#loading').hide();
} else {
document.getElementById("lp").classList.add("hidden");
document.getElementById("np").classList.remove("hidden");
$('#loading').hide();
}
});
};
Here, I have wrote $("#lp").html(summery);, in that div I have to append html which comes from var summery = SubscriptionoptioncompanylistFactory.getSummary(id);. But this is not going to append the data. In console I can see that data comes in summary variable. How can I do?
have a look at below modifications
Use angular ng-show for showing/hiding elements
Use data binding and avoid Jquery like Dom manipulation
<div class="col-xs-3" ng-repeat="item in companyData">
<a ng-click="getPackageInfo({{item.iCompanyID}},'{{item.vCompanyName}}')" class="block panel padder-v bg-primary item">
<span class="text-white block">{{item.vCompanyName}}</span>
</a>
<div id="packagehtml"></div>
</div>
<div id="lp" ng-show="lbVisible" class="col-md-12 listing-div hidden">{{summaryBinding}}</div>
and the controller would look like :
$scope.pData = [];
$scope.getPackageInfo = function (id, name) {
$scope.name = name;
var summery = SubscriptionoptioncompanylistFactory.getSummary(id);
$scope.lbVisible = true; //document.getElementById("lp").classList.remove("hidden");
$('.packages-data').html('');
$scope.loadingVisible = true; //$('#loading').show();
SubscriptionoptioncompanylistFactory.getPackageInDetail(id).
success(function (data) {
if (data != 0) {
$scope.summaryBinding = summery; // $("#lp").html(summery); // this is used to append the data
$scope.npVisible = false; // document.getElementById("np").classList.add("hidden");
Array.prototype.push.apply($scope.pData, data);
$scope.loadingVisible = false; // $('#loading').hide();
} else {
$scope.lbVisible = false; //document.getElementById("lp").classList.add("hidden");
$scope.npVisible = false; //document.getElementById("np").classList.remove("hidden");
$scope.loadingVisible = false; // $('#loading').hide();
}
});
};
your snippet is not showing elements that you use :
np, #loading so just find them and add the `ng-show` with the proper scope variable : `npVisible , lbVisible , loadingVisible`
and note that we add the data using summaryBinding
hope this helps :)

Categories

Resources