So I'm trying to set up a post function using Angular. I've got a HTML form which has two text boxes (for user input) and a drop down menu for selecting a number of choices (so the user fills out the form and submits data to server).
Binding the two text boxes is fine but I don't know how to bind the two options in my array as choices in the drop down menu?
(Heres a fiddle:http://jsfiddle.net/gtv7s8h3/2/ )
Form:
<form>
<input type="text" id="name" ng-model="myForm.Title" ng-minlength="5" ng-maxlength="20"> title <br/>
<input type="text" id="name" ng-model="myForm.Content" ng-minlength="5" ng-maxlength="20"> content <br />
<select ng-model="CategoryId" ng-options="item.name for item in CategoryId"></select>
<button ng-click="myForm.submitTheForm()">Submit Form</button>
</form>
Angular POST:
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myForm = {};
$scope.myForm.Title = "";
$scope.myForm.Content = "";
$scope.CategoryId = {
data: [{
id: '316556404cac4a6bb47dd4c7ca2dac4a',
name: 'name1'
}, {
id: '306e3d9a6265480d94d0d50e144435f9',
name: 'name2'
}]
};
$scope.myForm.submitTheForm = function(item, event) {
var dataObject = {
Title : $scope.myForm.Title,
Content : $scope.myForm.Content,
CategoryId : $scope.CategoryId
};
var responsePromise = $http.post("/url", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
});
You're trying to bind the categoryID to you array and your ngOptions expression does not loop through your array. You need to bind the categoryId value to a different model.
Add a model for your categoryID:
$scope.myForm.categoryId = null;
and change your select markup:
<select ng-model="myForm.categoryId" ng-options="item.id as item.name for item in CategoryId.data"></select>
Related
I am confused about why I am getting this specific malfunction, I am unable to get a default value for my select dropdown list. My goal is to have "Choose Board" as the default but despite many trials, I have been unable to get this as the default value.
I have attempted a variety of solutions: AngularJS - Set default value on select inside a ng-repeat & How to have a default option in Angular.js select box
Without any luck.
My HTML Tags:
<select name="boardInput" class="form-control"
ng-required="true"
ng-init="form.boardInput = boards[0]"
ng-model="form.boardInput"
ng-options="board.name for board in boards">
</select>
My JS controller code
//TRELLO CONTROLLER
$scope.baseBoards =[{
id: false,
name: "Choose Board"
}];
$scope.getBoards = function() {
trello.getBoards('me', function(error, boards){
if(error){
log("Could Not Get Boards: ", error);
} else {
log("found " + boards.length + " boards");
$scope.boards = $scope.baseBoards.concat(boards);
}
});
};
The result is a field being added and set as the default, in the above code the null field disappears after any of the others are selected.
any help is much appreciated.
Try
<select name="boardInput" class="form-control"
ng-required="true"
ng-model="form.boardInput"
ng-options="board.name for board in boards">
</select>
and in your Controller
$scope.form.boardInput = "Choose Board"
If it works then you can replace the text with your desired variable such as $scope.baseBoards[0].name.
Please check this updated answer. For now your trello.getBoards I have commented, once you add it in your code, uncomment it and comment var boards this variable.
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope) {
$scope.boards = [];
$scope.baseBoards = [{
id: false,
name: "Choose Board"
}];
$scope.getBoards = function() {
/* trello.getBoards('me', function(error, boards) {
if (error) {
log("Could Not Get Boards: ", error);
} else {
log("found " + boards.length + " boards");
$scope.boards = $scope.baseBoards.concat(boards);
}
}); */
//You will get boards data from your trello.getBoards method but I dont have access it so declaring local variable.
var boards = [{
name: 'one'
}, {
name: 'two'
}, {
name: 'three'
}]
$scope.boards = $scope.baseBoards.concat(boards);
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app='app' ng-controller='myController' ng-init="getBoards()">
<select name="boardInput" class="form-control" ng-required="true" ng-init="form.boardInput = boards[0]" ng-model="form.boardInput" ng-options="board.name for board in boards">
</select>
</div>
I am new to Angular js and I want to try the following.
I have an Object Array that come from Database. This is the url(example): http://localhost:3000/items/showAll
I have yet implemented the Add, Edit, Update, Delete (Crud operation in backend with nodejs and express js and frontend with angularjs) but my problem is with the checkbox.
I have in a table in my database a field "state", typ boolean default 0 (1 or 0 value).
I have a list of items(for example 100) and want to select with a checkbox in ng-repeat one or more items and send the value(1) to my filed state in the database. My logic is: I need to bind a single item id with the checkbox, then add a value to the checkbox and if is checked send it to the database.
<input type="checkbox" ng-model="state" parse-int ng-true-value="'1'" ng-false-value="'0'" class="form-check-input" >
[{"id":1,"name":"item1","state":0}]
What can I in my controller do?
Updated:
Code: Controller
$scope.createState = function() {
var postItem = {
id : $scope.id,
state : $scope.state
};
itemsService
.createItem(postItem)
.then(
function successCallback(response, data) {
$scope.clearForm();
},
function errorCallback(error, data, status, haders, config) {
console.log("Error getting: " + data);
}
);
};
Service:
var pathItems = "/items/add";
this.createItem = function(postItem) {
return $http.post(pathItems, postItem)
};
html ng-repeat:
<input type="checkbox" ng-true-value="1" ng-false-value="0" ng-model="item.state" ng-click="createState(item.id)">
Update the database, api
addItem: function(item, id, callback) {
return database.query("Update items SET state=? WHERE id=?", [item.state, id], callback);
},
router.post('/update/', function(req, res, next) {
items.addItem(req.body, function(error, count) {
if (error) {
res.json(error);
} else {
res.json(req.body);
}
});
});
This can update the database and I can do this from a bootstrap modal. I wanted to do this with a list of one checkbox per user, but I don't now what to do in AngularJS.
As far as I can understand from your question every time a checkbox is clicked you want to make an API call with the appropriate state. Attach the state to the ng-model of the checkbox. Then on ng-click call a function that will make an API call to update the database,
You can have a look at this code pen for the demo
HTML
<body ng-app="app" ng-controller="controller">
<div ng-repeat="item in data">
{{item.name}}
<input type="checkbox" ng-true-value="1" ng-false-value="0" ng-model="item.state" ng-click="makeAPICall(item.id)"><br>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</body>
Javascript
angular.module("app", [])
.controller("controller",
function($scope) {
$scope.data = [
{ id: 1, name: "item1", state: 0},
{ id: 2, name: "item2", state: 1},
{ id: 3, name: "item3", state: 0},
{ id: 4, name: "item4", state: 1},
{ id: 5, name: "item5", state: 0}
];
$scope.makeAPICall = function(itemID){
console.log("Item with id "+itemID+" was changed");
// Make API call here
};
}
);
The code updated in my question can update the database. For example, if userID=1, check/uncheck the user and update the database. In Angularjs HTML I can do this with a bootstrap modal. Click to a button and check/uncheck the checkbox.
I have a form that looks like this:
<form id="myForm" ng-submit="submitForm()">
<select name="ItemName" ng-controller="ItemController">
<option value="" selected disabled>Select</option>
<option ng-repeat="item in items track by $index" value="{{item.Id}}">{{item.Name}}</option>
</select>
<input type="text" name="Description" />
<button type="submit">Submit</button>
</form>
My AngularJS FormController then does the following:
form.controller.js
app.controller('FormController', function($scope, $http) {
$scope.submitForm = function () {
$http({
method: 'POST',
url: '/Path/To/MVC/Action',
data: { json: JSON.stringify($('#myForm').serializeArray()) }
})
.success(function(data) {
console.log('success');
})
.error(function(error) {
console.log('failure);
});
};
});
I want my MVC controller to receive a json string that looks like this:
{
"Name": "some item name",
"Description": "some item description"
}
With serialize(), I got something like:
Name=some%20item%20name&Description=some%20item%20description
...and with serializeArray(), I got something like:
[{
name: "Name",
value: "some item name"
},
{
name: "Description",
value: "some item description"
}]
How do I get the JSON string in the format I'm looking for?
Is this what you are looking for? I am a little unclear with what items is, etc:
https://plnkr.co/edit/IFHNtxS226Hq0cCMJYi1?p=preview
$scope.submitForm = function(formData){
console.warn(formData);
$http({
method: 'POST',
url: '/Path/To/MVC/Action',
data: { json: formData }
})
.success(function(data) {
console.log('success');
})
.error(function(error) {
console.log('failure');
})
}
});
Are you using WebAPI?
You can replace your select for this:
<select id="selectId" type="text" ng-required="true" name="nameOfSelect" class="form-control" ng-model="yourModel.ObjectForThisSelect" placeholder="String Inside you Select"
ng-options="info.Value as info.Text for info in items>
</select>
then you should post back "yourModel" object, this way Angular when posting back will serialize only the selected option value.
Additionally in case you are using WebApi you can check in your WebApiConfig class, Register(HttpConfiguration config) method, that you are formatting Json strings in the desired format: i.e.
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
I am new to angular js programming so please excuse me if my question is naive.
I am populating a list of checkboxes depending upon values inside a json object.
I am using ng-repeat to iterate through the list of keys & values received & display the check box. When each of the check box is clicked I am making a server call to get relevant data. The data I receive should be populated in a dropdown list only when it is clicked & the dropdown should disappear on un-click. I want to capture the dropdown selected option after the user selects it.
I am stuck as to how to get it.
My code for reference :
HTML :
<div class="container" ng-controller="OptionsController" >
<div ng-repeat="(key, value) in options" ng-if="value === 'text'">
<!-- {{key}} : {{value}}-->
<input type="checkbox" ng-click="getDistinct(key)"/>
<label>{{key}}
</label>
<div class="animate-show">
<select id="selector" ng-model="QueryFormData.Graph.selected">
<option ng-repeat="name in QueryFormData.Graph.options"
ng-value="name">{{name}}</option>
</select>
</div>
</div>
</div>
Controller code :
myApp.controller('OptionsController', ['$scope', '$http', '$location', 'datashare',
function($scope, $http, $location, datashare) {
//$scope.options = datashare.jsonData;
$scope.options = {
"_id": "571a0fcfaa6d92581ec99b2e",
"Name": "text",
"isstring": "text",
"value1": "number",
"value": "number",
"status": "text",
"ItantaTime": "time"
};
$scope.keyArr = [];
$scope.QueryFormData = {
Graph: {
options: [
'Line Graph'
],
selected: 'Line Graph'
},
displayValue: ''
};
$scope.getDistinct = function(key) {
if ($scope.keyArr.indexOf(key) == -1) {
$scope.keyArr.push(key);
var ServerAddr = "http://localhost:2000/getDistinct/" + key;
console.log("Server Addr :" + ServerAddr);
$http.get(ServerAddr, {
headers: {
'Content-Type': 'application/json'
}
})
.success(function(result) {
console.log(result);
})
.error(function(data, status) {
console.log(data)
});
}
console.log("changed : " + key);
};
}
]);
With current code I am seeing all the dropdowns at once. I want to show the dropdowns as a toggle functionality on check box selection.
Any help is highly appreciated.
First, you don't need ng-if. Use the built-in filter:
<div ng-repeat="(key, value) in options" ng-if="value === 'text'">
Can be
<div ng-repeat="(key, value) in options | filter: { value: 'text' }">
For your filtering problem, you can again use the filter in select elements to only get the dropdown values you want. Your JSON response must have a filterable property though... So, please post your JSON.
You use it like this:
<select ng-options="item.key as item.name for item in collection| filter:{ someProperty: true }">
I have a dropdownlist of U.S. States which is populated from a call to our web api. I have an edit page that fills in a user's details and I need to bind that dropdownlist to the state in the user's information. I'm sure this has something to do with ng-options, but I do not know how to implement it.
Here is my HTML for the dropdownlist:
<select data-ng-model="form.vchOfficeStateVchID" ng-options="s as s.StateVchID for s in userdetails.vchOfficeStateVchID" style="height:25px">
<option value="">--Select State--</option>
<option ng-repeat="state in states" value="state.StateVchID">{{state.StateVchID}}</option>
</select>
The function in my controller that populates the dropdownlist is:
getStates();
function getStates() {
operatorService.getallstates()
.success(function (data) {
$scope.states = data;
});
};
It returns an array which has the state abbreviation as its key "StateVchID" (I didn't create this database).
The user info is returned in the controller with the following function:
$scope.showDetails = function (user) {
$scope.noUser = false;
var userid = user.UserID;
operatorService.getuserdetails(userid)
.success(function (data) {
$scope.userdetails = data;
$scope.form.vchOfficeStateVchID = userdetails.vchOfficeStateVchID;
$scope.form.vchOfficeCountryVchID = userdetails.vchOfficeCountryVchID;
});
$scope.viewUser = true;
};
In the user's details, the State Abbreviation is held in the vchOfficeStateVchID field.
How do I get my dropdownlist to display the user's correct state? Basically, I need state.StateVchID = userdetails.vchOfficeStateVchID.
Any assistance is greatly appreciated!
Have a look at this example:
HTML
<div ng-app="myApp" ng-controller="myController">
<select name="vchOfficeStateVchID" ng-model="form.vchOfficeStateVchID" ng-options="s.StateVchID as s.Name for s in states">
<option value="">--Select State--</option>
</select>
<br/>
<div>
<h3>
Selected ID:
</h3>
{{form.vchOfficeStateVchID}}
</div>
</div>
JavaScript
var app = angular.module("myApp", []);
app.controller("myController", ["$scope", function($scope){
$scope.userdetails = {
vchOfficeStateVchID: 3
}
$scope.form = {};
$scope.states = [
{
Name: "New York",
StateVchID: 1
},
{
Name: "Texas",
StateVchID: 2
},
{
Name: "Las Vegas",
StateVchID: 3
},
{
Name: "Hawaii",
StateVchID: 4
}
];
$scope.form.vchOfficeStateVchID = $scope.userdetails.vchOfficeStateVchID;
}]);