ng-change not working in Select - angularjs

I don't know what happen but this function seems like not working at all.
Here is my view:
<tr>
<th>Category</th>
<td>
<select class="form-control" ng-model="masterlist.category_id" ng-options="c.category_id as c.category_name for c in category" required data-ng-change="getSubCategory(c.category_id)"></select>
</td>
</tr>
<tr>
<th>Sub Category</th>
<td>
<select class="form-control" ng-model="masterlist.sub_category_id" ng-options="c.sub_category_id as c.sub_category_name for c in subCategory" required></select>
</td>
</tr>
Angular JS
$scope.getSubCategory = function (category_id) {
$http.get('/MasterList/SubCategory' + category_id).then(function ($response) {
$scope.subCategory = $response.data;
});
}
Controller:
public ActionResult SubCategory(int id)
{
db.Configuration.ProxyCreationEnabled = false;
return Json(db.Sub_Category.Where(x => x.active_flag == true && x.category_id == id).ToList(), JsonRequestBehavior.AllowGet);
}
I check on the console but nothing's error and here is the inspect element view:
My main goal is to once category is selected, the display for sub category will be only those under the category.
Thanks in advance for the help.

Your select element's ng-model is set to masterlist.category_id. So you should pass that to your getSubCategory method.
<select class="form-control" ng-model="masterlist.category_id"
ng-options="c.category_id as c.category_name for c in vm.category"
required data-ng-change="vm.getSubCategory(masterlist.category_id)"></select>
Also you need to send a request with the url pattern SubCategory/3 where 3 is the category id value. With your current code it is going to make a request to SubCategory3 and you will see a 404 error if you inpsect your browser network tab.
You should add a / between the catetory_id variable and the action method name,
$http.get('Home/SubCategory/' + category_id)
I also recommend moving your http calls to a data service which can be injeccted to your controller. Als, you should not hard code the url's like that in your js file. Try to use the Url.Action helper method to generate the proper relative urls to your action method/api endpoints as explained in this post and this post.

Change the scope only when the value changes.
if($scope.subCategory != $response.data)
$scope.subCategory = $response.data;

Related

getting the updated value of inputs in ng-repeat | Angular Js

I have a inputs in a table filled out with ng-repeat, i want to be able to get the updated values by one click for all inputs.
My View:
<tr ng-repeat="sf in selectedFacture">
// displaying default values in the input
<td><input class="facture_item_name" ng-model="sf.facture_item_name" value="{{sf.facture_item_name}}" type="text"/></td>
<td><input class="fcls_crt" ng-model="sf.fcls_crt" value="{{sf.fcls_crt}}" type="number"/></td>
<td><input class="fpiece" ng-model="sf.fpiece" value="{{sf.fpiece}}" type="number"/></td>
<td colspan="4"><input type="text" class="form-control note" ng-model="sf.note" value="{{sf.note}}"/></td>
<tr>
<td ng-click="updateFacture(sf.id,sf,sf.facture_type,sf.item_id)">SUBMIT</td>
</tr>
</tr>
JS:
// getting new values and send them to server side
$scope.updateFacture=function(id,sf,type,item_id){
var url = '../php/history.php';
var func = "updateFacture";
sf = sf || {};
var editedQuanCls= sf.fcls_crt,
editedQuan_piece= sf.fpiece,
editedQuan_cls_crt_gate= sf.fcls_crt_gate,
editedQuan_piece_gate= sf.fpiece_gate,
editedNote= sf.note;
var data = {"function": func,
"factureId":id,
"item_id":item_id,
"facture_type":facture_type,
"editedQuanCls":editedQuanCls,
"editedQuan_cls_crt_gate":editedQuan_cls_crt_gate,
"editedQuan_piece":editedQuan_piece,
"editedQuan_piece_gate":editedQuan_piece_gate,
"editedNote":editedNote};
var options = {
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
alert("success")
},
error:function(request,response,error){
alert("errro: " + error)
}
};
$.ajax(options);
}
I tried to put the updated button in a td aside to the inputs and it works fine, but this will update each row separately, but my need is to updated them all in one click.
I'll attach a screen shot of my view.
Many Thanks in advance
<input class="facture_item_name" ng-model="sf.facture_item_name" value="{{sf.facture_item_name}}" ng-change="updateValues(sf.facture_item_name)" type="text"/>
$scope.updateValues=function(value){
$scope.sf.facture_item_name=value;
}
What you need is a wrapper function.
First add a button on the page that covers the All option like:
<button ng-click="updateAllFacture()">SUBMIT ALL</button>
Then add the wrapper function. All this does is loop through each item in the list and call the update function.
The wrapper function would look like:
$scope.updateAllFacture=function(){
angular.forEach($scope.res, function(sf, index) {
$scope.updateFacture=function(sf.id,sf,sf.facture_type,sf.item_id );
});
};
If you have an awful lot of items then there will be a lot of calls back to your api. Consider submitting all the inputs in the form as a post instead - then there will be just one call back, but you will need to program your controller for that.

Grails GSP Loop through an index and do somthing with selected lines

In an Index-gsp, I want to be able to select an arbitrary number of lines and then by clicking a link send all those lines to a controller for processing e.g. creating new objects of a different kind.
I've no idea how selection can be done or how to collect these selected lines in a GSP. Maybe I should use a checkbox on each line if that's possible?
It's a list of products which is displayed using a modified index.gsp.
Each product-line has a checkbox in front.
What I want is to make a list of the products that are checked an then transmit this list to a controller.
a part of this index.gsp:
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
<li><g:link class="create" action="createOffer"><g:message code="default.new.label" args="[entityName]" params="toOffer" /></g:link></li>
</ul>
</div>
<div id="list-prodBuffer" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<table>
<thead>
<tr>
<td> Välj</td>
<td> ID</td>
</tr>
</thead>
<tbody>
<g:each in="${prodBufferList}" status="i" var="prodBuffer">
<tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
<td><g:checkBox name="toOffer" value="${prodBuffer.id}" checked="false" /></td>
<td>${prodBuffer.id}</td>
So this not an ordinary form, just a list where I want to use a link to transmit it to the controller.
I'm a beginner and have no idea how to do it.
You can collect all necessary data from page using javascript, and then send all data to your controller for processing.
There are a lot of ways to do it.
For example send via JQuery:
<script>
//some code
var items = [1,2,3];
//some code
$('#add-location').click(function () {
$.ajax({
type: "POST",
url: "${g.createLink(controller:'myController', action: 'myControllerMethod')}",
data: {items: items},
success: function (data) {
console.log(data)
}
});
});
</script>
I will answer this but have to slow down since it feels like i am beginning to write your project:
In gsp you will need to have a hidden field followed by a check box amongst data you are trying to capture, checkbox should contain all the data elements required to build your output.
<g:hiddenField name="userSelection" value=""/>
<g:checkBox name="myCheckBox" id='myCheckBox' value="${instance.id}"
data-field1="${instance.field1}" data-field1="${instance.field1}"
checked="${instance.userSelected?.contains(instance.id)?true:false}" />
In the java script segment of the page you will need to add the following
This will then auto select selection and add to javascript array
// Customized collection of elements used by both selection and search form
$.fn.serializeObject = function() {
if ($("[name='myCheckBox']:checked").size()>0) {
var data=[]
$("[name='myCheckBox']:checked").each(function() {
var field1=$(this).data('field1');
var field2=$(this).data('field2');
data.push({id: this.value, field1:field1, field2:field2 });
});
return data
}
};
Most importantly will your data sit across many different gsp listing pages if so you will need to hack pagination:
//Modify pagination now to capture
$(".pagination a").click(function() {
var currentUrl=$(this).attr('href');
var parsedUrl=$(this).attr('href', currentUrl.replace(/\&userSelection=.*&/, '&').replace(/\&userSelection=\&/, '&'));
var newUrl=parsedUrl.attr('href') + '&userSelection=' + encodeURIComponent($('#userSelection').val());
window.location.href=newUrl
return false;
});
Then in the controller parse the JSON form field and make it into what you want when posted
def u=[]
def m=[:]
if (params.userSelection) {
def item=JSON.parse(params.userSelection)
item?.each {JSONObject i->
// When field1 is null in JSON set it as null properly
if (JSONObject.NULL.equals(i.field1)) {
i.field1=null
}
if (resultsGroup) {
if (!resultsGroup.contains(i.id as Long)) {
u << i
}
} else {
u << i
}
}
m.userSelected=item?.collect{it.id as Long}
m.results=u
}
return m

Use AngularJS Variable, where another AngularJS Variable matches its ID

I have an ng-repeat statement where I want to show an image. The image however, should be chosen from where the ng-repeat's ID matches the image object's ID.
I am unsure of how to do this properly, here is psuedo code of what I am trying to do.
<tr ng-repeat="user in rosterData | orderBy:'name'">
<img ng-src="{{champion.imagename WHERE user.id = champion.id}} />
</tr>
Remember that champion.id is an object of champions, so I want to make sure I get the right champion.name to match with the right champion.id when it matches the current ng-repeat user.id
It would be better if you could check those logic inside the controller:
<tr ng-repeat="user in rosterData | orderBy:'name'">
<img ng-src="{{getImage(user.id)}} />
</tr>
In your controller:
$scope.getImage = function(userId) {
var image = "defaultimage";
$scope.champions.forEach(function(champion) {
if(champion.id===userId) {
image = champion.image;
}
});
return image;
}
You will have to put a method in "ng-src" statement, pass the id as a parameter - > iterate array, find match and so on.
Method should be added in controller to $scope property, than just call it :)

Angular.js - search filter for object with ng-repeat

I'm apologizing for messy description of my problem. I hope you understand it.
I have this HTML code:
<form>
<input ng-model="attr.query" type="text" placeholder="{{attr.attr_name}}" ng-repeat="attr in attrs">
</form>
<table>
<tr ng-repeat="element in elements">
<td ng-repeat="(key, value) in element">{{value}}</td>
</tr>
</table>
JS controller:
$scope.attrs = [{'descr':'descr1'},{'descr':'descr2'}];
$scope.elements = [{'property1" : 'value1', 'property2' : 'value2'},{'property1" : 'value3', 'property2' : 'value4'}];
I need to filter each by query from input. But i need to filter only with the same attr as in input field.
I have some troubles to apply filter to array of objects.
Thanks
If I understand you correctly (I don't have enough rep to ask in a comment, sorry), you want to filter the data on one or more of several attributes.
The simplest way to do this is probably by defining a custom filter function accessible to your scope. AngularJS's filter filter will happily accept that as an evaluator.
$scope.customFilter = function(item) {
var passed = true;
if(/* the item doesn't pass muster */) {
passed = false;
}
return passed;
}
If it helps, I put together a fiddle to demonstrate. (NB. The query fields are case-sensitive.)

How to ng-repeat into html table with multiple levels of json?

I have an object of social media stats. I'm trying to ng-repeat them into a table. Here's my plunker.
HTML:
<table>
<tr ng-repeat="(metric, metricData) in data">
<td>{{metric}}</td>
<td>{{metricData}}</td>
</tr>
</table>
Controller object:
$scope.data = { buzz:0,
Delicious:121,
Facebook:
{
like_count: "6266",
share_count: "20746"
},
GooglePlusOne:429,
LinkedIn:820,
Twitter:4074
};
I run into a problem when I get to the Facebook results. Within the <td> that entire object gets displayed (as it should be with how I have my code setup). But what I'd rather have happen is to repeat through that object and display the key and value in the cell.
I tried doing something looking to see if metricData is an object and doing some sort of ng-repeat on that. But I wasn't having luck with that. Any idea on how I can display the inner object (keys & value) within the cells?
You can define a scope function returning the type of metricData :
$scope.typeOf = function(input) {
return typeof input;
}
And then you can display it according to its type :
<tr ng-repeat="(metric, metricData) in data">
<td>{{metric}}</td>
<td ng-switch on="typeOf(metricData)">
<div ng-switch-when="object">
<div ng-repeat="(key, value) in metricData">
<span>{{key}}</span>
<span>{{value}}</span>
</div>
</div>
<span ng-switch-default>{{metricData}}</span>
</td>
</tr>
You can see it in this Plunker
Sounds like you'll need a specific directive that wires up children to be recursive, take a look at this example: Recursion in Angular directives
What you'd check on is if what you need to repeat is an object and not a value, then add the new element compile it, and start the process over again.
I'm assuming you want each of those values to have their own line but you don't explain exactly how you want it to work. I think the matter would best be handled by passing a clean version of what you want to the ng-repeat directive. I'm assuming you want two rows for facebook in your sample. You could create a filter to flatten the metrics so there are properties "Facebook_like_count" and "Facebook_share_count" (PLUNKER):
app.filter('flatten', function() {
function flattenTo(source, dest, predicate) {
predicate = predicate || '';
angular.forEach(source, function(value, key) {
if (typeof(value) == 'object') {
flattenTo(value, dest, predicate + key + '_');
} else {
dest[predicate + key] = value;
}
});
}
return function(input) {
var obj = {};
flattenTo(input, obj, '');
return obj;
}
});
Then your repeat can use the filter:
<tr ng-repeat="(metric, metricData) in data|flatten">

Resources