I am facing serious issues with drop down its design get weird when populating the drop down when using this chunk of html I am getting this design:
index.html
<select id="chkveg" ng-model="ArrangeSurveyCtrl.sections" ng-options="item
as item.section for item in ArrangeSurveyCtrl.sections" multiple="multiple">
I tried with static value and it worked perfect:
index.html
<option value="AJ">AJ</option>
<option value="Valuation">Valuation</option>
<option value="Comps">Comps</option>
index.js
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function() {
alert($('#chkveg').val());
})
});
getAllSections();
function getAllSections() {
ArrangeSurveyService.getAllSections().
then(function(result) {
var serverData = result.data;
if (serverData.success) {
if(serverData) {
vm.sections = serverData.result;
console.log(vm.sections);
}
}
}, function(err) {
//some error
console.log("Error: ", err);
$("#preloader").css("display", "none");
})
}
Related
I am using dataFactory for getting collection by making api call.
productApp.factory("productDataFactory", function($http){
return {
getUnits: function() {
return $http.get('/unit').then(function(resp) {
return resp.data; // success callback returns this
});
},
getCommodities: function() {
return $http.get('/commodity').then((resp) => {
return resp.data;
})
}
};
});
I use commodities collection in ng-options to populate options of select element.
<select ng-model='selected_Commodity' ng-change="updateGST()" name="commodity" id="commodity" ng-options = " c as c.commodity_name for c in <%= JSON.stringify(commodities) %> track by c "class="form-control selectpicker" data-size="4" data-live-search="true" data-index="5" >
<option value="" ng-hide='selected_Commodity'>Select Commodity</option>
</select>
I am updating collection on a event. I am getting updated values in log. But It does not get reflected in my view.
var getCommodities = function() {
var deferred = $q.defer();
productDataFactory.getCommodities().then((data) => {
if (data.type === 'success') {
debugger;
console.log("Inside factory ");
console.log(JSON.stringify( data.commodities ));
deferred.resolve(data.commodities);
} else {
// $scope.commodities = [{name : data.type + data.msg}]
deferred.reject([{name : data.type + data.msg}]);
}
})
return deferred.promise;
}
$('#commodityModal').on('hide.bs.modal', function () {
$scope.commodities = []
getCommodities().then((data) => {
$scope.commodities = data
console.log("Inside Hide ");
console.log(JSON.stringify( $scope.commodities ));
$("#commodity").selectpicker('refresh')
console.log("Refreshed");
})
})
Please help me how can I rebind my select elements with updated values.
Put this line inside a timeout like this and add timeout as a dependency
$timeout(function(){
$("#commodity").selectpicker('refresh');
});
Change the ng-options
FROM
ng-options = " c as c.commodity_name for c in <%= JSON.stringify(commodities) %> track by c "
TO
ng-options = " c as c.commodity_name for c in commodities track by c "
I am new to Angular 1,so I am stuck with building a dropdown box dynamically using angular.
Below is my code
var app = angular.module('myApp', []);
app.controller('TestCtrl', function($scope, $http) {
I have created an onchange function getTypeName() and have passed the parameters using get method and retrieved the result as json .
$scope.getTypeName = function (type) {
$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
var data = response.data;
for(i = 0; i < data.length; i++) {
//code to build dropdown
}
},
);
}
});
Below is my response,
[
{"id":"001","name":"ABC"},
{"id":"002","name":"DEF"},
{"id":"003","name":"GHI"}
]
I want to build a dropdown box using this response within the get method function success using for loop.Please provide a solution to solve this out.
you do like this
in app.js
$scope.getTypeName = function (type) {
$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
$scope.data = response.data;
},
);
}
});
in your html
<select id="ddl" model="ddldata" typeof="text"required>
<option data-ng-repeat="ProjectName in data" value="{{ProjectName.id}}" ng-bind={{ProjectName.name}}">
</select>
You can try this,
$scope.yourOptions = [];
$scope.getTypeName = function (type) {$http.get('get-type-name',
{ params:
{
type: type
}
}).then(
function(response){
var data = response.data;
$scope.yourOptions = data;
},
);
}
});
in html,
<select class="form-control" ng-model="whatever" >
<option ng-repeat="x in yourOptions " value="{{x.id}}">{{x.name}}</option>
</select>
Here is an example of dynamically populating select options from an http get https://plnkr.co/edit/7PS7LBBNZA2cNzMorrB9?p=preview
<select ng-model="selectedItem">
<option ng-repeat="o in options">{{o.name}}</option>
</select>
$scope.getTypeName = function() {
$http.get('https://jsonplaceholder.typicode.com/users').then(
function(result) {
$scope.options = result.data;
},
function(error) {
console.log(error);
}
);
};
I want to set the dropdown value on basis of json result returned by mvc controller.
Code behind (mvc controller)
public ActionResult GetProject(int Id)
{
using (ManagementSystemEntities db = new ManagementSystemEntities())
{
return Json(db.SelectProject(Id).ToList(), JsonRequestBehavior.AllowGet);
}
}
Above lines are working correctly. It returns list of projects.
List returned :
Id Title
1 test
2 test2
I want to select dropdown value as "test" by its value which is Id = 1
HTML >>
<select ng-options="project.Title for project in projectList" id="ddlProject" ng-model="selectedProject">
<option value="">-- Select Project --</option>
<option data-ng-repeat="project in projectList" value="{{project.Id}}"> {{project.Title}}</option>
</select>
There is no issue which is related to angular loading. Everything working fine. Only need is to set the dropdown value on basis of ajax result.
Ajax Call (angular code) >>
Code for Populating dropdown options : (Working fine)
$http.get(service_url + "Project/GetProject", { params: { "id": 0 } })
.success(function (response) {
if (response.length < 1) {
// No Record
}
else {
$scope.projectlist = response;
}
})
.error(function (data) {
fnsuccessmodal("error in load", "error");
});
Code for set value in dropdown :
$http.get(service_url + "Project/GetProject", { params: { "Id": 1 } })
.success(function (response) {
if (response.length < 1) {
// No Record
}
else {
$.each(response, function (index, item) {
//console.log(item.ProjectId); it is displaying 1 as in console screen I am only getting project which have Id equal to 1.
$scope.selectedProject = $scope.projectList[item.ProjectId]; // This line not working
});
}
})
.error(function (data) {
fnSuccessModal("Error in Load", "Error");
});
Please help.
This is some recomendations. If you don´t want them go to the (BUT) bellow. First you should return a list if you going to pass a collection, and just one item if you want to search by id and the id is the primary key of the project.
I have write this here so there are possible some errors.
public ActionResult GetProject(int? Id)
{
using (ManagementSystemEntities db = new ManagementSystemEntities())
{
return Json( id.HasValue ? db.SelectProject(Id).FirstOrDefault() : db.SelectAllProjects().ToList(), JsonRequestBehavior.AllowGet);
}
}
this way to get the list you can change your code to
$http.get(service_url + "Project/GetProject", { })
.success(function (response) {
if (response.length < 1) {
// No Record
}
else {
$scope.projectlist = response;
}
})
.error(function (data) {
fnsuccessmodal("error in load", "error");
});
to get the selected project, by your logic
$http.get(service_url + "Project/GetProject", { params: { "Id": 1 } })
.success(function (response) {
if (response) {
$scope.selectedProject = response;
});
}
})
.error(function (data) {
fnSuccessModal("Error in Load", "Error");
});
for the markup, you should not have an an ng-options inside ng-repeat
<select ng-options="project as project.Title for project in projectList track by project.Id" id="ddlProject" ng-model="selectedProject">
<option value="">-- Select Project --</option>
</select>
BUT if you don´t want to change the things that i talked about just change this and it shoul work. It´s your choice
$http.get(service_url + "Project/GetProject", { params: { "Id": 1 } })
.success(function (response) {
if (response.length < 1) {
// No Record
}
else {
$.each(response, function (index, item) {
//console.log(item.ProjectId); it is displaying 1 as in console screen I am only getting project which have Id equal to 1.
$scope.selectedProject = item:
});
}
})
.error(function (data) {
fnSuccessModal("Error in Load", "Error");
});
and the markup you have to introduce a track by so
<select ng-options="project as project.Title for project in projectList track by project.Id" id="ddlProject"
ng-model="selectedProject">
<option value="">-- Select Project --</option>
</select>
here is a plunker that i created with my opinion where the http.get where replaced by timeouts
here you can find documentation for ngRepeat track by
Best,
I'm using AngularJS and have the following problem with ngdialog.
I have a function that opens a dialog and then saving dialog form elements which are then displayed in a table.
The table is updated without reloading the page, but to reopen the dialog goes with previous data.
I want to add a new item without reloading the page. Now I do, but I have to reload the page because when recreating another I get with the new data from the previous dialog
var app = angular.module('AlarmsAddOn', ['ngTable', 'ngDialog'])
app.controller('AlarmsAddOnCtrl', function($scope, $http, $filter, ngTableParams, datas, ngDialog, tags, tagIndex, $timeout){
var self=this;
//initializing $scope
$scope.data=datas;
$scope.tagss=tags;
$scope.tagIndex=tagIndex;
$scope.tableParams = new ngTableParams({
page: 1,
count: 10,
filter: {
message: ''
},
sorting: {
tag_id: 'asc'
}
},
{
total: $scope.data.length,
counts:[],
getData: function($defer, params) {
var orderedData = params.sorting() ?
$filter('orderBy')($scope.data, params.orderBy()) :
$scope.data;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
//edit tag settings
self.edit_addon = function(key){
$http.post('/', key).then(function(results){
if (results.status==201)
{
$scope.typemsg="alert alert-success";
$scope.msgmsg = "The tag settings has been updated. The new Trigger Value is: "+key.value;
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
else
{
$scope.typemsg="alert alert-danger";
$scope.msgmsg = "Server Error";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
});
};
//delete tag settings
self.delete_addon = function(key){
if(confirm("Are you sure to remove the tag settings")){
var url='/'+key.tag_id+'/'+key.trigger;
$http.delete(url).then(function (results) {
console.log(results);
if (results.status==200)
{
for(var i=0; i<$scope.data.length; i++)
{
if($scope.data[i].tag_id == key.tag_id && $scope.data[i].trigger == key.trigger)
{
var p=i;
}
}
$scope.data.splice(p,1);
$scope.tableParams.reload();
$scope.typemsg="alert alert-success";
$scope.msgmsg = "The tag settings of "+key.tag_name+" has been deleted";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000)
}
else
{
$scope.typemsg="alert alert-danger";
$scope.msgmsg = "Server Error";
$scope.alertmsg = false;
$timeout(function () { $scope.alertmsg = true; }, 2000);
}
});
}
};
//create new tag settings
self.savetag = function () {
$scope.tag=self.tag;
$http.post('/', $scope.tag).then(function (results) {
if (results.status==201)
{
$scope.data.unshift(self.tag);
$scope.tableParams.reload();
// window.location.reload();
}
else
{
}
});
ngDialog.close();
};
//show form to add new tag settings
self.insert_modal_windows_addon = function()
{
ngDialog.open({ template: '/assets/insert.html', controller: 'AlarmsAddOnCtrl', scope: $scope, cache: false});
};
});
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Add New Tag</h3>
<form name="tag_form" ng-submit="AOC.savetag()" >
<select class="form-control" name="tagid" placeholder="Tag Id" ng-model="AOC.tag.tag_id">
<option value="" disabled selected>Tag Name</option>
<option ng-repeat="k in tagss" value="{{k}}">{{tagIndex[k]}}</option>
</select>
<select class="form-control" name="tagtriggertype" placeholder="Trigger Type" ng-model="AOC.tag.trigger" style="margin:20px auto;">
<option value="" disabled selected style="color:#333;">Trigger Type</option>
<option value="hight">hight</option>
<option value="low">low</option>
</select>
<input type="number" class="form-control" name="tagtriggervalue" placeholder="Trigger Value" ng-model="AOC.tag.value", style="margin:20px auto;"/>
<button class="btn btn-sm btn-primary" type="submit">
<span class="glyphicon glyphicon-floppy-save"></span>
Submit
</button>
</form>
</div>
</body>
</html>
I am trying to write a custom filter. It's purpose is to do one of three things, based on a drop down menu. It needs to either show only hidden items, only notHidden items, or all items.
Here is my drop down menu.
<select class="span1" ng-model="itemfilter.hidden'">
<option value="">All</option>
<option value="hidden">Hidden</option>
<option value="shown">Shown</option>
</select>
Here is the HTML for the ng-repeat and filter
<div ng-repeat="item in items | hiddenFilter:itemfilter.hidden:'hidden"> </div>
Here is the Custom Filter
app.filter('hiddenFilter', function($_ ) {
return function( items, show_or_hide, attribute ) {
var shownItems = [];
$_.each(items, function(item) {
if(show_or_hide === 'shown') {
if (item[attribute] === true)
shownItems.push(item);
} else{
if (item[attribute] !== true)
shownItems.push(item);
}
});
return shownItems;
};
});
I am having trouble figuring out how to make the drop down menu change what this filter displays, any help would be greatly appreciated.
Edits --
Once I passed in the attribute correctly I started getting different results. The all and hidden options now show only nonHidden items, and the shown options shows only hidden items. Still not sure where I am going wrong.
Edit 2 --
Tried to make a jsfiddle for it here http://jsfiddle.net/mindstormy/RVB8A/1/
Fixed the code for you. Working Demo
<div ng-app="app" ng-controller="exampleCtrl">
<select class="span1" ng-model="itemfilter.hidden">
<option value="all">All</option>
<option value="hidden">Hidden</option>
<option value="shown">Shown</option>
</select>
<div ng-repeat="item in items| hiddenFilter:itemfilter.hidden:'hidden'">{{item.name}}, {{item.hidden}}</div>
</div>
var app = angular.module('app', []);
app.controller('exampleCtrl', function ($scope) {
$scope.items = [{
name: 'Foobar',
hidden: true
}, {
name: 'Foobar',
hidden: false
}, {
name: 'Barfoo',
hidden: true
}, {
name: 'Barfoo',
hidden: false
}, {
name: 'FB',
hidden: false
}];
$scope.itemfilter = {};
$scope.itemfilter.hidden = "all";
});
app.filter('hiddenFilter', function () {
return function (items, show_or_hide, attribute) {
var shownItems = [];
if (show_or_hide === 'all') return items;
angular.forEach(items, function (item) {
if (show_or_hide === 'shown') {
if (item[attribute] === true) shownItems.push(item);
} else {
if (item[attribute] !== true) shownItems.push(item);
}
});
return shownItems;
};
});