So I am currently working on an application that uses WebAPI and AngularJS to search for some data from a SQL table and display it on a webpage for the user to select multiple individual rows of data. I am inserting the selected rows into a separate JSON array (availableclients) that I would like to insert into a separate SQL table. What is the best method for me to take my array of JSON data and insert it into a different SQL table. I will attach the code I am currently using to get the data.
Controller.js
var app = angular.module('myApp', []);
app.controller("myController", function ($scope, $http) {
function getCert(myid) {
$http.get('api/Cert/Get/', { params: { id : myid } })
.success(function (data) {
$scope.selectedclients = data;
})
}
$scope.searchClick = function() {
getCert($scope.myid);
}
$scope.moveItem = function (item, from, to) {
var idx = from.indexOf(item);
if (idx != -1) {
from.splice(idx, 1);
to.push(item);
}
};
$scope.availableclients = [];
});
HTML
<html data-ng-app="myApp">
<body data-ng-controller ="myController">
My_ID: <input type="text" ng-model="my_id" />
<input type="submit" value="Search" ng-click="searchClick()" />
<select size="10" multiple ng-model="selected" ng-options="i.unit_id for i in selectedclients" style="width: 400px"></select>
<div class="btn-group">
<button title="Remove From List" class="btn btn-default" ng-click="moveItem(available[0], availableclients,selectedclients)"><i class="glyphicon glyphicon-chevron-left"></i></button>
<button title="Add To List" class="btn btn-default" ng-click="moveItem(selected[0], selectedclients,availableclients)"><i class="glyphicon glyphicon-chevron-right"></i></button>
</div>
<select size="10" multiple ng-model="available" ng-options="i.unit_id for i in availableclients" style="width: 400px"></select>
</body>
</html>
The code I have is working fine I am just at a loss for how to take my availableclients JSON array and insert it into my SQL table. This is probably really easy to do but all my searches are coming up blank on what I am looking for exactly. Any help is appreciated. Thanks!
EDIT 1: On recommendation of a comment I am adding the Controller I used for the Web API get. Again thanks for any advice!
public class CertController : ApiController
{
CertEntities objapi = new CertEntities();
[HttpGet]
public IEnumerable<AngularCoCSelect_Result> Get(int id)
{
return objapi.AngularCoCSelect(id).AsEnumerable();
}
}
It is quite wide question... also you are showing the client code and nothing from the backend which eventually will store the data (suspecting as you put asp.net tag also)
So based on that You can use Entity Framework to store your data into a database. You may find a lot of articles on the internet about implementing this approach.
This solution as guide line
need back-end api that accept array of object (json) for your clients ASP.NET or PHP then
You need to add function in Angular within your controller for submit client data to the server using $http.put or $http.post
$scope.submitClientData = function(){
$http.post('webapi/clients' , { clients:$scope.availableclients })
}
You may call function from submit button
<button ng-click='submitClientData()'>Save</button>
Related
Using AngularJs 1.6.7, I have created a table which pulls project details from a database and displays these details within a table. Each row has a modify/update button using ng-show/hide. When modify is clicked, the div changes to editable input fields, when update is clicked, the new input data will be update in the database.
I am trying to access input items within an ng-repeat and using ng-model to bind the input to update projects in a database using Flask.
The problem is that when I access the data in AJS once update is clicked, no data has binded to the new input values.
My HTML looks like this.
<tr data-ng-repeat="(key, value) in projects" >
<td>
<div data-ng-hide="edditable_project[value.project_name]">{[value.project_name]}
</div>
<div data-ng-show="edditable_project[value.project_name]">
<input class="form-control" data-mg-model="updatedProjectName" value="{[value.project_name]}">
</div>
</td>
<td>
<button class="btn btn-danger add-on pull-right btn-sm" data-ng-click="removeProject(value)">Delete</button>
<button class="btn btn-primary add-on btn-sm pull-right" data-ng-hide="edditable_project[value.project_name]" data-ng-click="modify(value.project_name)">Modify</button>
<button type="submit" class="btn btn-success pull-right btn-sm " data-ng-show="edditable_project[value.project_name]" data-ng-click="update(value)">Update</button>
</td>
</tr>
And my controller looks like this:
app.controller('projectSettingsController', ['$scope', '$http', function($scope, $http) {
$scope.modify = function(project) {
$scope.edditable_project[project] = true;
};
$scope.update = function(project) {
data = {
project_name: $scope.updatedProjectName,
}
console.log($scope.updatedProjectName);
// Update project.
$http.post('/api/project/update-project', data).then(function(response) {
toastr.success(response.data);
});
$http.get('/api/project/get-all-project-details').then(function (response) {
$scope.projects = response.data;
});
$scope.edditable_project[project] = false;
};
}]);
The current output for ng-model="updatedProjectName" is undefined.
Am I doing something wrong within the scope?
well you should define your binding vairable in the scope of your controller like
$scope.updatedProjectName =""; by default it`s null as you have described, but for all your inputs you will have one data binding, i think you should have some
$scope.data={};
tr data-ng-repeat="(key, value) in projects" >
<input data-ng-model="data[key]">
</tr>
and you don`t need to set value in your input, ng-model will make it for you
You are trying to access a variable which is defined inside of ng-repeat's scope. What you would want to do in this case is pass value and work on the project variable inside the update function.
Change your mark up to data-mg-model="value.project_name". Now the ng-model binds to same. When the update completes set the latest data(if needed) as properties on project. It will reflect in the view because of 2 way data binding
Inside update you should do as follows
$scope.update = function(project) {
// Update project.
$http.post('/api/project/update-project', project).then(function(response) {
toastr.success(response.data);
// If needed set new properties on the project variable
// based on the response
});
}
You seem to have a typo:
<input class="form-control" data-mg-model="updatedProjectName" value="{[value.project_name]}">
Use ng-model instead of mg-model.
I'm generating dozens of forms on my page. Each form has several parameters (not the same for each form). I'm generating my forms as such (simplified):
<div ng-repeat='module in modules'>
<form ng-submit='submitModule(module)'>
<div ng-repeat='arg in module.args'>
<input ng-model='models[module.name][arg.name]' id="{{ arg.name }}">
</div>
</form>
</div>
You can see I'm trying to assign a unique ng-model to each input parameter by using a two dimensional array models[module.name][arg.name].
Because I am planning on submitting this as JSON, the idea was that I could just do models[some_module] in my controller to get the full JSON, and then just post along.
Unfortunately this isn't working, when trying models['test_module'] I get undefined, instead of my object. There are no errors elsewhere in the code, I've tested extensively. The problem comes from the use of multi-dimensional arrays here which is apparently a big no-no.
How should I handle my situation? IE: several forms, several inconsistent parameters, and a need to POST every param together as JSON.
EDIT: For info, my controller looks like:
angular.module('app')
.controller('InputCtrl', function($scope, InputSvc) {
$scope.models = {};
InputSvc.list().success(function(modules) {
$scope.modules = modules;
$scope.models['test_module'] = {}
});
$scope.submitModule = function(module) {
console.log($scope.models['test_module']);
};
});
Perhaps you could give each form a controller so the model is scoped to the form instance rather than the parent:
<div ng-repeat='module in modules'>
<form ng-controller="FormCtrl" ng-submit='submitModule(module)'>
<div ng-repeat='arg in module.args'>
<input ng-model='formData[arg.name]' id="{{ arg.name }}">
</div>
</form>
</div>
Then your FormCtrl would have the submit method and the model:
angular.module('app')
.controller('FormCtrl', function($scope) {
$scope.formData = {};
$scope.submitModule = function(module) {
console.log($scope.formData);
};
});
Here is a Codepen
I have a form to enter a list of key value pairs. When I enter data into the input fields or add a new keyvalue pair everything displays fine on the client side and I can see the Model updating. The problem comes when I go to save the newly created list. The list get passed to the angular save function just fine with all the data in place. The problem occurs between the angular save function and my MVC controller save function. The right number of key value pairs get sent to the MVC controller functions parameters, but all of the information has now been set to null.
So on the client side my model looks like this.
[{"Key":"this","Value":"has"},{"Key":"data","Value":"in"},{"Key":"it","Value":"see"}]
which is what I want, but when it reaches my MVC controller as a parameter it looks like this.
[{"Key":null,"Value":null},{"Key":null,"Value":null},{"Key":null,"Value":null}]
Which is not what I want. Any help with this will be greatly appreciated. Thank You.
Here is my MVC controller function.
public JsonResult SaveSettings(List<KeyValuePair<string, string>> replacementPaths)
{
JobSchedulerConfig config;
config = Biz.GetConfig();
config.ReplacementPaths = replacementPaths;
return null;
}
My Angular controller and save logic.
$scope.save = function () {
SettingsService.saveSetting($scope.settings)
.success(function (data) {
//alert(data);
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
});
};
SettingsApp.factory('SettingsService', ['$http', function ($http) {
var SettingsService = {};
SettingsService.getSettings = function () {
return $http.get('#Url.Action("GetReplacementPaths", "Setting")');
};
SettingsService.saveSetting = function (data) {
//alert(data);
alert(data.toSource());
//data = angular.stringify(data);
return $http.post('#Url.Action("SaveSettings", "Setting")', data );
};
return SettingsService;
}]);
And my view markup.
<div ng-app="SettingsApp">
<div ng-controller="SettingsController">
<div ng-repeat="kvp in settings">
<input ng-model="kvp.Key" />
<input ng-model="kvp.Value" />
<button ng-click="delete(settings, kvp)">Delete</button>
</div>
<button class="btn btn-default" ng-click="addSetting()">Add Setting</button>
<button type="submit" name="config" ng-click="save()" class="btn btn-default btn-primary">Save Config</button>
{{settings}}
</div>
</div>
Again thanks for any help.
I'm rather new to web development and I am trying to get a better understanding of servers and databases and what the limitations are of client-side development.
Right now, I'm learning AngularJS and I have been able to create simple CRUD applications such as a to-do list or online store. Currently, I have always been creating the data for my web applications through regular JavaScript Arrays/Objects.. but now I want to be able to permanently edit/change this data through my own CMS user interface.
Some research has led me to use JSON and the angular $http service to request JSON data from the server.
Now, I am trying to update this JSON data Asynchronously with angularJS and I'm not sure how to do this (see below for my attempt).
Simple To-Do List Application
<body ng-controller="ToDoCtrl">
<div class="container">
<div class="page-header">
<h1>
{{todo.user}}'s To Do List
<span class="label label-default" ng-hide="incompleteCount() == 0"
ng-class="warningLevel()">
{{ incompleteCount() }}
</span>
</h1>
</div>
<div class="panel">
<div class="input-group">
<input class="form-control" ng-model="actionText">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="addItem(actionText, todo.items)">Add</button>
</span>
</div><!-- end input-group -->
<table class="table table-striped">
<thead>
<tr>
<th>Descriptions</th>
<th>Done</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todo.items | checkedItems: showComplete | orderBy: 'action'">
<td>{{item.action}}</td>
<td><input type="checkbox" ng-model="item.done"></td>
<td><button ng-click="deleteItem(item, todo.items)" class="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
<div class="checkbox-inline">
<label><input type="checkbox" ng-model="showComplete">Show Complete</label>
</div>
<div class="input-group">
<button ng-click="save()" class="btn btn-primary">Save Changes</button>
<p>{{msg}}</p>
</div>
</div><!-- end panel -->
</div>
<!-- Vendor JS -->
<!-- Angular -->
<script src="vendors/angular.min.js"></script>
<!-- Modules -->
<script src="app.js"></script>
</body>
app.js
var model = {
user: "Alex"
};
angular.module('todoApp', [])
.run(function($http) {
$http.get("todo.json").success(function(data) {
model.items = data;
});
})
.controller('ToDoCtrl', ['$scope', '$http', function($scope, $http) {
$scope.todo = model;
$scope.incompleteCount = function() {
var count = 0;
angular.forEach($scope.todo.items, function(item) {
if (!item.done) {
count++
}
});
return count;
};
$scope.warningLevel = function() {
return $scope.incompleteCount() < 3 ? "label-success" : "label-warning";
};
$scope.addItem = function(actionText, sourceArray) {
sourceArray.push(
{
action: actionText,
done: false,
}
);
$scope.actionText = '';
};
$scope.deleteItem = function(item, sourceArray) {
for(var i = 0, j = sourceArray.length; i < j; i++) {
if(item.action == sourceArray[i].action) {
sourceArray.splice(i, 1);
return;
}
}
};
$scope.save = function() {
$http.post('C:\Users\Alex\Desktop\Development\"Web Design"\2015\todoApp\public\src\todo.json', $scope.todo.items).then(function(data) {
$scope.msg = 'Data saved '+ JSON.stringify($scope.todo.items);
});
};
}])
.filter("checkedItems", function() {
return function(items, showComplete) {
var resultArr = [];
angular.forEach(items, function(item) {
if(item.done == false || showComplete == true) {
resultArr.push(item);
}
});
return resultArr;
}
});
I used this Post for the $scope.save function, but I receive an error: "XMLHttpRequest cannot load. Cross origin requests are only supported for protocol schemes: http, data, chrome..."
$scope.save = function() {
$http.post('C:\Users\Alex\Desktop\Development\"Web Design"\2015\todoApp\public\src\todo.json', $scope.todo.items).then(function(data) {
$scope.msg = 'Data saved '+ JSON.stringify($scope.todo.items);
});
};
Basically, I just want to update my todo.json file with the current contents of my $scope.todo.items array. I think the simplest way would be to delete the current contents of the JSON data and replace with current contents of $scope.todo.items, but I don't know much about this stuff.
Thanks for any help.
Let's start with some concepts first:
1.- a JSON file is just a text file, it can be a product of a database query or it can be generated dynamically by a server, but at the end of the day is just a text file.
2.- the $http service deals with request to HTTP servers, like the Apache Web Server, or NodeJS Http Server, running your software with backend technology, there's a multitude of servers and some can run in your machine as well as remotely.
3.- GET and POST are HTTP methods, that must be made to a server running your backend. The most common one, the GET method is usually used to get data from a server, like text files, or JSON files.
4.- In a file server like the one Windows provides you for local development, the GET method can bring up files from your file system (like "todo.json"). This file server is really basic, it just accepts GET requests and that's all it should accept.
5.- In your backend software, you define an Endpoint, that should be an address where your backend is ready to receive a POST request, and you also need to define what does this POST request do.
It's a long step between going from your angular file to defining an endpoint in a server, you will go across different technologies, the Angular framework is not a backend technology, it's a frontend library.
If you want to get into these concepts, a TODO List project is a great first project, sites like http://www.todobackend.com/ can show you all sort of TODO projects in a myriad of different backends and frontends.
Right now I am working with AngularJS on a web interface which should have similar behavior like Dev HTTP Client. I can't find a way how to add headers in the way like DHC does.
I'm trying to make it somehow like this, but it isn't working since array is initialized empty:
<div ng-repeat="header in headersCollection.headers">
<input ng-model="header.name" type="text"/> :
<input ng-model="header.value" type="text"/>
</div>
<button type="button" ng-click="addNewHeader()">Add</button>
Headers should be stored inside this object and be available for creating, editing and removing through web interface. Just like in DHC.
$rootScope.headersCollection = {
headers : []
}
Any idea / link / answer are highly appreciated and answered immidiately.
Thank you.
Just make an "empty" header object in the headers collection. See http://jsfiddle.net/e8MEx/
Of course you will want to throw in some validation to make sure they are values before adding another one and potentially add the ability to remove an item:
JavaScript:
var mod = angular.module("myApp", []);
mod.run(["$rootScope", function($rootScope) {
//start the array with one empty value for header
$rootScope.headersCollection = {
headers : [{name: "", value: ""}]
}
}]);
mod.controller("MainController", ["$scope", "$rootScope", function ($scope, $rootScope) {
$scope.headersCollection = $rootScope.headersCollection
$scope.addNewHeader = function () {
//push a new empty value onto the array.
$scope.headersCollection.headers.push({name: "", value: ""});
}
}]);
HTML:
<div ng-app="myApp" ng-controller="MainController">
<div ng-repeat="header in headersCollection.headers">
<input ng-model="header.name" type="text"/> :
<input ng-model="header.value" type="text"/>
</div>
<button type="button" ng-click="addNewHeader()">Add</button>
<p>{{headersCollection.headers}}</p>
</div>