I have an input value that I want to style, based on the value I receive back from the angular variable. So in my cshtml, I have:
<input type="{{d.input_type}}" ng-style={{d.input_type}} == "radio" ? 'width:40px;' : 'width:100px;" #*class="form-control"*# #*ng-model="Customer.CustStatus"*# name="question_answer" id="question_answer" required >
Then in my angular .js file I have the following:
$scope.Question = {
Question1: '',
input_type: ''
}
$http.get('/Home/getUserInfo')
.then(function (response) {
$scope.Question = response.data;
console.log("status:" + response.status);
console.log("data: " + $scope.Question);
}).catch(function (response) {
console.error('Error occurred:', response.status, response.data);
}).finally(function () {
console.log("Task Finished.");
});
Based on the value I receive back (which is either "radio" or "text"), I want to have different styling. For example, I want to have a radio button height of 20px and text must be 40px. How would I go about having conditional styling on my input value, based on the text value I receive back from "input_type".
Any help would be greatly appreciated.
The syntax is
<input ... ng-style="{'width': d.input_type == 'radio' ? '40px' : '100px'}" ...>
So you first specify the property you're going to set and then its value based on your logic.
Related
please help me with my problem I'm a little new to angularjs, my problem is that I need to be able to set the default value in the select option when there is only one item because it's a dynamic select option, it has another dropdown with many items but it's okay , what is needed when only one item must be selected in the select option using ng-options
<select class="form-control form" ng-model="relatedTo" style="height: 40px;" ng-options="c.CUSTCODE as c.CUSTNAME + ' - ' + c.CUSTCODE for c in customers | filter:code" > </select><span style="color:red" ng-show="type === 9 || type !== 9"></span>
ANGULARJS
$http.post('commandCenter.aspx/allCustomer', {}).then(
function onSuccess(response) {
$scope.customers = JSON.parse(response.data.d);
console.log($scope.customers); },
function onError(response) {
console.log('error !!! ');
});
Picture no.1 It's okay in this picture because he has a lot of list of items.
Picture no.2 When there is only one item, it must be default or selected.
What #MrJami said. In code something like
$http.post('commandCenter.aspx/allCustomer', {}).then(
function onSuccess(response) {
$scope.customers = JSON.parse(response.data.d);
if ($scope.customers.length === 1) {
$scope.relatedTo = $scope.customers[0].CUSTCODE;
}
console.log($scope.customers); },
function onError(response) {
console.log('error !!! ');
});
Is there a way to tell ng-model if your value is 0 then show the placeholder value not the ng-model value.
The reason for this is I have an issue where the UX requires the ng-model to be one value while the business logic requires it to be another.
Something like this.
Controller
$scope.qty = 0;
//...some calculation that requires $scope.qty to be a number
HTML
<input ng-model="qty" placeholder="N/A">
<!-- This will show 0 not N/A as qty has a value-->
I do understand you can edit the functionality of ng-model with the following.
ng-model-options={getterSetter: true}
This does solve this issue in a single ng-model like above but what about when the qty is in a ng-repeat?
In the real world we are making a page that auto calculates the amount of items a user should order based on there inventory. If the inventory is 0 the placeholder is used if it is changed by the user then the value they entered in is used.
As there is more then one product they can order we have this in an ng-repeat.
Controller
$scope.products = [{
//...product data
inventory : 0
}]
HTML
<tr ng-repeat="product in products track by $index">
<td>
<input ng-model="product.inventory" placeholder="N/A">
</td>
</tr>
You can try the setter getter method but as the only value you get is the value entered into the input box you lose the context of which item the user is referring to unless you create a setter getter function for each product.
Try this. You can define a getter function for ng-model directive if you use ng-model-options by setting getterSetter as true. ng-model-options is used to modify the behaviour of ng-model.
<input ng-model="getterSetter" placeholder="N/A" ng-model-options={getterSetter: true}>
// Controller function
$scope.getterSetter = function(value) {
if(value == 0) {
return "N/A";
}
else {
return value;
}
}
You can ngModelOptions, Object to tell Angular exactly when to update the Model.
<input ng-model="updateModel" placeholder="some text" ng-model-options={updateModel: true}>
// Controller method
$scope.updateModel= function(value) {
if(value <= 0) {
return "some text";
}
else {
return value;
}
}
I'm using a select form with data retrieved from a JSON url. When I select something, I want the value to be put into $scope.afspraak.groep. For some reason, the value returns to the original value which is empty.
Here is my code:
<select id="selectgroep" name="selectgroep" class="form-control" size='5' ng-model="afspraak.groep" ng-options="t.id as t.id for t in objecten" ng-click="test()">
</select>
$scope.afspraak = {
groep: '',
};
$scope.passData = function(data) {
$scope.afspraak.groep = data;
}
$scope.test = function() {
console.log($scope.afspraak);
}
I have used various methods such as changing ng-click to passData(afspraak.groep), but it still doesn't work. The weird thing is that in another partial, I have the exact similar code and that does work shown here:
<select id="selectvak" name="selectvak" class="form-control" size='5' ng-model="user.vakid" ng-options="t.id as t.id for t in vak" ng-click="getKlas(user.vakid); test()">
</select>
$scope.user = {
vakid: '',
};
$scope.test = function() {
console.log($scope.user);
}
$scope.getKlas = function (ID){
afsprakenService.getKlassen(ID)
.success(function (klas){
$scope.klas = klas;
$scope.alerts.push({ type: 'success', msg: 'Retrieved'});
})
.error(function (error) {
$scope.alerts.push({ type: 'danger', msg: 'Error retrieving! ' + error.message});
});
};
What am I doing wrong here? The only difference that I see is the method in the second select form which is getKlas where I pass the ng-model to use in another function.
Edit: this is now solved! It turns out that a label class is what was causing the deletion. I removed it by accident and it works now!
To set a models value from a select it is sufficient to have a ng-model on it. In case you want to do some extra action when selecting an option you should use ng-change and not ng-click.
A good way to debug your models, to check in real time if it was updated and view its values do something like this
<pre>{{ myModel | json }}</pre>
Here is a working fiddle example: http://jsfiddle.net/jub58sem/2/
I have input field which I am using for autocomplete and populate on the fly by executing http requests. I am getting such object as example:
{
id:1,
name:'ABC'
}
I want to display name for a end user but later on when input has been selected I want to use it as id in my further processing. But ng-model converts my object into the string and I loose my id.
In general all works fine but my issue is that when user select something, lets say string "ABC" it means nothing for me unless I can tied it to "ID" which has been returned by my API. Only if I know ID I can continue future processing.
Could you please help me to figure out, what should I do in order to capture fromSelected as object but still show friendly text to user?
Thanks for any help!
Code:
HTML:
<input type="text" ng-model="fromSelected" placeholder="Country, city or airport" typeahead="place.readableName for place in getPlace($viewValue, 'en')" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control">
JS:
app.controller('PlaceController', function($scope, $http, searchData) {
$scope.fromSelected = '';
$scope.toSelected = '';
$scope.$watch('fromSelected', function(newValue, oldValue){
if (newValue !== oldValue) searchData.setTravelFrom(newValue);
});
$scope.$watch('toSelected', function(newValue, oldValue){
if (newValue !== oldValue) searchData.setTravelTo(newValue);
});
// Any function returning a promise object can be used to load values asynchronously
$scope.getPlace = function(term, locale) {
return $http.get('http://localhost:8080/api/places/search', {
params: {
term: term,
locale: locale
}
}).then(function(response){
return response.data.map(function(item){
return {
'id': item.id,
'name': item.name,
'readableName': item.name + ' (' + item.id + ')'
};
});
});
};
});
The following is my html on my view.
I have the following on my html 1)Text Box (for user to enter key words) 2)Apply Button :which on click gets the text typed inside the text box and other filters (which is not shown) here, makes an ajax call to bind data to the grid as shown.
My problem :
On the kendo grid , one of my column is a template column as shown below. The editor template is defined for that column as seen below.Am trying to suggest to the user "suggestions/suggested tags" as and when he/she types inside the text area (which is inside the grid).
for e.g.when the user types say A;B;C as when a semicolon is entered I would like to suggest tags for;in this case "A" and then "B" and so on.. In order to get this done I would like to add a text changed event-like event to the text area in editor template. Is it possible? If so may i know how to go about it?
<input type="text" id="tb_Search" />
<input type="button" value="Apply" style="width: 140px" onclick="ApplyFiltersToFetch()" />
#(Html.Kendo().Grid<CurationModuleV3.Models.Model1>()
.Name("TGrid").Pageable
().EnableCustomBinding(true)
.DataSource(dataSource =>
{
dataSource.Ajax()
.Update(update => update.Action("RefreshGrid", "Home"))
.PageSize(10)
.Model(model =>
{
model.Id(t =>t.UserID);
}
).Batch(true).ServerOperation(false);
})
.Columns(columns =>
{
columns.Bound(t => t.UserID).Visible(false);
columns.Bound(t => t.Tags).Title("Tags").EditorTemplateName("TagColumnTemplate").ClientTemplate("<pre name='Tags' id='#=UserID#' style='height: 60px;overflow: auto;margin-top: 0px;margin-bottom: 0px;'>#= Tags#</pre>").Width(180).HtmlAttributes(new { style = "padding:0;top:0;" });
}).ToolBar(toolbar =>
{
toolbar.Save().SaveText("Save all changes");
})
.Editable(editable => editable.Mode(GridEditMode.InCell)).HtmlAttributes(new { style = "height:450px;" }).Scrollable().Sortable().ClientDetailTemplateId("templateForInnerUserGrid"))
<script>
function ApplyFiltersToFetch() {
var searchTextValue;
var grid = $('#TGrid').data("kendoGrid");
searchTextValue = document.getElementById("tb_Search").value;
if (!(searchTextValue == "")){ $('#TGrid').show();
$.ajax({
url: '#Url.Action("FetchT", "Home")',
data: { searchText: searchTextValue},
type: 'POST',
dataType: "json",
success: function (result) {
grid.dataSource.data(result);
grid.refresh();
grid.dataSource.page(1);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});}
</script>
/*****Editor Template*********/
#model string
#Html.TextAreaFor(t => t, new {rows = 4, wrap = "hard",style = "text-overflow:ellipsis; display:block; width:94%; height:100%;font-family:Segoe UI , Verdana, Helvetica, Sans-Serif;font-size: 0.85em;" }
)
EDIT:
May be i was not clear enough. Am not trying to bind any event for my search text box here. I just had my code to show how I bind my data to my grid. I do not want en event for my search text box, however I would like to have an event handler binded to my text area inside the grid (that shows up on edit). On typing inside my grid I would like to suggest to users tags.
add the type to the script tag
<script type="text/javascript">
then change your function to
$('#tb_Search').on('keyup', function(){
//put the function here
});
Thanks Matt, for providing me the start. Hence I included the class name in the editor template as seen below
#model string
#Html.TextAreaFor(t => t, new {rows = 4,*#class="tagColEdit"*,wrap = "hard",style = "text-overflow:ellipsis; display:block; width:94%; height:100%;font-family:Segoe UI , Verdana, Helvetica, Sans-Serif;font-size: 0.85em;"}
)
then I added the event handler as suggested by Matt
$(function () {
$('#TGrid').on('keypress', '.tagColEdit', function () {
alert('Hello');
})
})