How to do CRUD operation update in angular js? - javascript

Hii i am new to angular js ,right now i am working on the crud operation in angular js , i dont know how to do update the data in angularjs which is consuming rest api calls. could you pls help me out ?
my view :
<div ng-repeat="phone in phones">
<p>{{ phone.sequenceNumber}}. {{ phone.phoneNumber }} ({{ phone.phoneType }}<span ng-if="phone.isPrimary"> primary</span>)</p>
<button ng-click="updatePhone()" ng-model="phone.phoneNumber" class="btn btn-small btn-primary">update</button>
</div>
</div>
</form>
my controller :
"use strict"
ContactApp.controller("StudentController", [
'$scope',
'$http',
'$state',
'$sce',
'UiString',
'Settings',
'EmergencyContact',
'MissingPersonContact',
'Address',
'Phone',
function($scope, $http,$state, $sce, UiString, Settings, EmergencyContact, MissingPersonContact, Address, Phone
) {
EmergencyContact.getContacts($scope.uid).then(function(contacts) {
$scope.emergencyContacts = contacts;
});
MissingPersonContact.getContacts($scope.uid).then(function(contacts) {
$scope.missingPersonContacts = contacts;
});
Address.getLocalAddress($scope.uid).then(function(address) {
$scope.localAddress = address;
});
Phone.getPhones($scope.uid).then(function(phone1) {
$scope.phones = phone1;
});
$scope.newPhoneNumber = '';
$scope.AddPhone = function() {
console.log("scope.newPhoneNumber",$scope.newPhoneNumber);
var newPhone = Phone.addPhone($scope.newPhoneNumber);
Phone.savePhone($scope.uid, newPhone).then(
function(response) {
$scope.phones.push(newPhone);
return console.log("question", response);
},
function(err) {
return console.log("There was an error "
+ err);
});
};
$scope.updatePhone = function() {
Phone.savePhone1($scope.uid, newPhone).then(
function(response) {
$scope.phones.push(newPhone);
return console.log("question", response);
},
function(err) {
return console.log("There was an error "
+ err);
});
};
}]);
my service :
'use strict';
angular.module('ContactApp')
.service('Phone', ['$q', '$http', 'Settings', function($q, $http, Settings) {
this.getPhones = function(id) {
var deferred = $q.defer();
if (id) {
$http.get(Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + id + '?token=' + Settings.getToken()).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
} else {
deferred.resolve({});
}
return deferred.promise;
};
this.addPhone = function(phoneNumber) {
var model =
{
"pidm": null,
"phoneType": "CELL",
"activityDate": null,
"isPrimary": null,
"phoneNumber": phoneNumber,
"sequenceNumber": null,
"status": null
};
return model;
}
this.savePhone = function(userId, phone) {
var deferred = $q.defer();
console.log(phone);
$http.post( Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + userId + '?token=' + Settings.getToken()
, [ phone ]).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
this.updatePhone = function(phoneNumber1) {
var model =
{
"pidm": 123456,
"phoneType": "CELL",
"activityDate": null,
"isPrimary": null,
"phoneNumber": phoneNumber1,
"sequenceNumber": null,
"status": null
};
return model;
}
this.savePhone1 = function(userId, phone1) {
var deferred = $q.defer();
console.log(phone1);
$http.put( Settings.getSetting('wsRootUrl') +
'/person/phone/v1/' + userId + '?token=' + Settings.getToken()
, [ phone1 ]).
success(function(response) {
deferred.resolve(response.data);
}).error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
}]);

~~~EDIT~~~~
Okay from what I gather this is what you want:
In HTML inside of ng-repeat:
<input type="text" ng-model="phone.phoneNumber" />
// at this point when the user types their new phone number in the "phone" object has already been updated (via two-way data binding).
Then if you want to save to database you can send to your service via the controller method $scope.updatePhone with the button.
<button ng-click="updatePhone(phone)">Update</button>
Then in the controller:
$scope.updatePhone = function (phone) {
console.log("this is the updated phone: ",phone);
console.log("this is the updated phones array: ",$scope.phones);
// you should see that the phone number has been updated in scope.
Phone.updatePhone(phone);
// this service call should be a post to the server, not a return object as the object has already been updated.
}
Hope this helps

You can find example here of CRUD operation in AngularJS with Web API to perform Create, Read, Update and Delete functionality. I hope it will be help to you.
CRUD Operation in AngularJS with Web API

Related

API, angularJS, to get datas

I never done angularJS from all my life and i am lost.
So i have done this file, to obtain datas from an api with a filter of time.
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
But i have no idea to make a controller adapter to this. What type of controller i can do ?
Every exemple are based on a fixed json file, with no parameters.
Moreover, i want, in HTML to imput the time filter, but i have totaly no idea of what to do for this. The example i have seen were to get datas, no to send.
Ps : I have made 2 days of research about this, i have never done front end programming in my life.
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application" ng-controller="SampleCtrl">
<label>Time Start:
<input type="text" ng-model="timeStart"/></label>
<label>Time End:
<input type="text" ng-model="timeEnd"/></label>
<button ng-click="getForecast()">Get Forecast</button>
<hr/>
<div>
<b>Forecast Result:</b>
</div>
<pre>{{forecastReport | json}}</pre>
</div>
Just inject the factory into your controller like this:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
Or with a component (cleaner):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }

Trying to access json-server data via a controller and factory in angular

I'm writing a very simple test app in angular js and am trying to display data stored on a json server to display in the view.
db.json is as follows:
{
"examples": [
{
"id": 0,
"name": "example 0",
"description": "Example 0 description."
},
{
"id": 1,
"name": "example 1",
"description": "Example 1 description."
}
]
}
controller is as follows:
angular.module('my_app')
.controller('ExampleController', ['$scope', 'exampleFactory', function ($scope, exampleFactory) {
$scope.example = exampleFactory.query({
})
.$promise.then(
function (response) {
var examples = response;
$scope.message = examples;
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
}])
factory is as follows:
.factory('exampleFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
return $resource(baseURL + "examples/:id", null, {
'update': {
method: 'PUT'
}
});
}])
;
And view is as follows:
<p>Test outside repeat: {{message}}</p>
<ul>
<li ng-repeat="example in examples">
<p>Test in repeat: {{message}}</p>
<p>{{example.name}}</p>
<p>{{example.description}}</p>
</li>
</ul>
The interesting thing here is that the data is being returned by the factory. In the above example the first test (outside the ng-repeat) returns the full set. However, nothing inside ng-repeat shows up.
I've got this working using a slightly different arrangement using a service but it doesn;t seem to be working using a factory.
Does anyone have any idea why this is and could they put me right?
Thanks
Stef
I think you just forgot to assign $scope.examples, so the ng-repeat had no data to loop over:
angular.module('my_app')
.controller('ExampleController', ['$scope', 'exampleFactory', function ($scope, exampleFactory) {
$scope.example = exampleFactory.query({
})
.$promise.then(
function (response) {
var examples = response;
$scope.message = examples;
$scope.examples = examples.examples; // I may be reading the JSON wrong here.
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
}])
I'd suggest using a factory as you can get the methods inside the factory before the factory has been returned. It's the revealing module pattern, good read here if your interested JavaScript Design Patterns
angular
.module('my_app')
.controller('ExampleController', ['$scope', 'exampleFactory',
function($scope, exampleFactory) {
function getMessageList() {
exampleFactory
.getMessages()
.then(function(messages) {
$scope.examples = messages;
})
.catch(function(response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
});
}
getMessageList();
}
])
.factory('exampleFactory', ['$http', 'baseURL',function($http, baseURL) {
function getMessages() {
return $http
.get(baseURL)
.then(function(jsonResp) {
return jsonResp.data;
})
.catch(function(error) {
//handle error if needed
console.log(error);
});
}
return {
getMessages: getMessages
};
}
]);
<p>Test outside repeat: {{examples}}</p>
<ul>
<li ng-repeat="example in examples">
<p>Test in repeat: {{message}}</p>
<p>{{example.name}}</p>
<p>{{example.description}}</p>
</li>
</ul>
Eventually sorted it by changing controller as follows:
.controller("ExampleController", function($scope, exampleFactory) {
exampleFactory.query(function(response) {
$scope.examples = response;
$scope.examples.$promise.then(
function (response) {
var examples = response;
$scope.message = examples;
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
});
});
Probably a little bit clunky and it would be nice to be able to reduce it further but as I'm very new to all this I'll go with this for now.

I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular

What am I missing ? I am new to Angularjs. Trying angularjs with asp.net mvc. I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular.
However, I get success otherwise using $.getJson of javascript but not using angularjs. What am I missing ? please guide. Thank you for replying any.
Following is my Service
EbsMvcApp.factory('classListService', function ($resource, $q)
{
var resource = $resource
(
'/Home/ClassList'
, {}
//{ method: 'Get', q: '*' }, // Query parameters
, { 'query': { method: 'GET' , isArray:false } }
);
function get($q)
{
console.log('Service: classListServic > Started');
var Defered = $q.defer();
resource.get
(
function (dataCb)
{
console.log('success in http service call');
Defered.resolve(dataCb);
}
, function (dataCb)
{
console.log('error in http service')
Defered.reject(dataCb);
}
);
return Defered.promise; // if missed, would throw an error on func: then.
};
return { get: get };
});
angular Controller:
var EbsMvcApp = angular.module('myApp', ['ngResource']);
//'classListService',
EbsMvcApp.controller
(
'myAppController',
['$scope','classListService','$q' , function ($scope, classListService, $q)
{
console.log('controller myAppController started');
var classList = classListService.get($q);
classList = classList.then(
function ()
{
(
function (response)
{
console.log('class list function response requested');
return response.data;
}
);
}
);
console.log(classList.ClassName);
console.log(classList);
console.log('end part of ctrl');
$scope.classList = classList;
$scope.SelectedClassID = 0;
$scope.message = ' message from Controller ';
}
]
);
Asp.net MVC Controller
namespace EBS_MVC.Controllers
{
public class HomeController : BaseController
{
ApplicationDbContext db = new ApplicationDbContext();
public JsonResult ClassList()
{
var List = new SelectList(db.tblClass, "ID", "ClassName");
return Json(List, JsonRequestBehavior.AllowGet);
}
}
}
Brower's response (F12):
ControllerTry1.js:11 controller myAppController started
serviceGetClassList.js:16 Service: classListServic > Started
ControllerTry1.js:28 undefined
ControllerTry1.js:29 c
ControllerTry1.js:31 end part of ctrl
angular.js:12520 Error: [$resource:badcfg]
[Browers response: screen shot][1]
Oky, finally, I got a solution using the $http service. from here
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/13/how-to-use-angularjs-in-asp-net-mvc-and-entity-framework-4.aspx
in csHtml file, a reference to the service.js and Controler.js is required.
I am not sure if I have added it earlier or later now. but its required.
ng-Controller:
EbsMvcApp.controller('ClassListController', function ($scope, ClassListService2) {
console.log('ClassListController Started');
GetClassList();
function GetClassList()
{
ClassListService2.GetJson()
.success(function (dataCallBack) {
$scope.classList = dataCallBack;
console.log($scope.classList);
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
console.log($scope.status);
});
}
});
ng-Service:
EbsMvcApp.factory('ClassListService2', ['$http', function ($http) {
console.log('ClassListService2 Started');
var list = {};
list.GetJson = function () {
return $http.get('/Home/ClassList');
};
return list;
}]);
csHtml View:
<div class="text-info" ng-controller="ClassListController">
<h3> Text from Controller: </h3>
#*table*#
<table class="table table-striped table-bordered">
<thead>
<tr><th>DisplayName</th><th>Value</th>
</thead>
<tbody>
<tr ng-hide="classList.length">
<td colspan="3" class="text-center">No Data</td>
</tr>
<tr ng-repeat="item in classList">
<td>{{item.Text}}</td>
<td>{{item.Value}}</td>
</tr>
</tbody>
</table>
Sorry for the delay, I just wrote up some code to quickly test the ngResource module as I haven't used it yet.
I've got the code working to do what you want using the ngResource module. I think part of the problem was that you was configuring the query method but calling the get method so your configurations was not applied.
Here is the service class that I wrote to test against a controller the same as yours.
(function () {
'use strict';
angular
.module('myApp')
.service('classService', ClassService);
ClassService.$inject = ['$resource', '$q'];
function ClassService($resource, $q) {
var resource = $resource
(
'/Home/ClassList',
{},
{
'get': { method: 'GET', isArray: true },
'query': { method: 'GET', isArray: true }
}
);
var service = {
get: get
};
return service;
////////////
function get() {
var Defered = $q.defer();
resource.get(function (dataCb) {
console.log('success in http service call');
Defered.resolve(dataCb);
}, function (dataCb) {
console.log('error in http service')
Defered.reject(dataCb);
});
return Defered.promise;
};
};
})();
The controller looks like this
(function () {
'use strict';
angular
.module('myApp')
.controller('classController', ClassController);
ClassController.$inject = ['$scope', 'classService'];
function ClassController($scope, classService) {
var vm = this;
vm.data = null;
activate();
/////////////
function activate() {
var classList = classService.get().then(function (response) {
console.log('class list function response requested');
vm.data = response;
console.log(vm.data);
});
console.log('end part of ctrl');
$scope.SelectedClassID = 0;
$scope.message = ' message from Controller ';
};
};
})();
I've included some of your original code just so you can see how it would fit in.
Glad to see you have got it working though!

AngularJs json URL changer

I'm working on some mega simple weather app in Angular for practice reasons and i'm stuck..
i have a angular json feed like this:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and it loads the feed in to the index.html. its all working and what i wand now is a input form on index that changes the Amsterdam part of the url on js/services/forcast.js where the above code is to another city so people can see their city weather.
See the demo here: http://dev.bigstoef.nl/workspace/shiva/weer/index.html
Ive tryd about all posable options about now and i'm 3 days further and its a no go. What is there correct way here?
First, create a "configurable" service :
app.factory('forecast', ['$http', function($http) {
var city;
var cities = {
amsterdam: 'Amsterdam,NL',
paris: 'Paris,FR'
};
var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
var other_params = 'lang=NL_nl&units=metric';
return {
setCity: function(cityName){
city = cityName ;
console.log(city);
},
getWeather: function(cityName){
console.log(city);
if(cityName) this.setCity(cityName);
if (!city) throw new Error('City is not defined');
return $http.get(getURI());
}
}
function getURI(){
return api_base_url + '?' + cities[city] + '&' + other_params;
}
}]);
Then you can create a controller like the following:
app.controller('forecastCtrl', ['$scope', 'forecast',function($scope,forecast){
$scope.city = 'amsterdam' ;
$scope.$watch('city',function(){
console.log($scope.city);
forecast.setCity($scope.city);
});
$scope.getWeather = function(){
console.log('get weather');
forecast.getWeather()
.success(function(data){
console.log('success',data);
$scope.weatherData = data;
}).error(function(err){
console.log('error',err);
$scope.weatherError = err;
});
};
}]);
To implement a template as the following
<link rel="stylesheet" href="style.css" />
<div data-ng-controller="forecastCtrl">
<form>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
</label>
<br/>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
</label>
<br/>
<button data-ng-click="getWeather()">Get Weather</button>
</form>
<p class="weather-data">
{{weatherData}}
</p>
<p class="weather-error">
{{weatherError}}
</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
You can view the code working here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview
You can return a function in your factory. Define your forcast as
app.factory('forecast', ['$http', function($http) {
return {
query: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
Then in your controller
forecast.query('Amsterdam,NL').success(function(data) {
$scope.weer = data;
});
Change service code to have a dedicated method which you can call multiple times with different parameters (cities):
app.factory('forecast', ['$http', function($http) {
return {
load: function(location) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
}
}]);
Then in controller you would be able to load forecat for other locations when you need:
forecast.load('Amsterdam,NL').then(function(data) {
$scope. weer = data;
});
Demo: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

From jquery to angularjs

i am using the below format to get a JSON object from my localhost. The JSON is pretty complicated and lengthy so , using jquery to populate the HTML is getting complicated.
function processmsg(msg) {
var jobj = JSON.parse(msg);
if (typeof jobj === 'object')
{
// Parse the JSON
}
document.getElementById("messages").innerHTML = globalTag;
}
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "1.json",
cache: false,
timeout: 50000,
success: function (data) {
processmsg(data);
if (!data) {
setTimeout(
waitForMsg,
1000
);
};
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
setTimeout(waitForMsg, 15000);
processmsg("error");
}
});
};
$(document).ready(function () {
waitForMsg();
processmsg("loading");
});
I would like to use the format like {{jobj.entries}}. something like this. This can be done on angularJS. can you guys please suggest me how to do the same in angular ?
i want to query the JSON every 1 min and when the data is found i want to cancel the interval. I dono how to do it in angularjs.
==================update================
i got below code snippet. It is working fine, But how do i stop the url query once the json object is obtained..
var app = angular.module('urlanalyzer', []);
app.controller('jsonController', function($scope, $http) {
$scope.getData = function(){
var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
$http.get(url)
.success(function(data, status, headers, config) {
console.log(data);
});
};
if (!$scope.data){
setInterval($scope.getData, 2000);
}
The issue here is the json object will be available after 3 sec only.
var app = angular.module('urlanalyzer', []);
app.controller('jsonController', ['$scope','$http','$timeout',function($scope, $http, $timeout) {
$scope.getData = function(){
var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
$http.get(url)
.success(function(data, status, headers, config) {
if(!data)
$timeout(function(){
$scope.getData()
}, 2000)
else{
$scope.myData = data.data? data.data:data;
$scope.showError = false;
}
})
.error(function(msg) {
$timeout(function(){
$scope.getData()
}, 2000)
$scope.processMessage(msg)
});
};
$scope.processMessage = function(msg){
if(angular.isString(msg))
$scope.errorMessage = msg;
else if(angular.isObject(msg)){
$scope.errorMessage = msg.message // the property you want;
}
$scope.showError = true;
}
$scope.getData();
}])
HTML:
<div ng-controller="jsonController">
<div ng-show="showError">
{{errorMessage}}
</div>
<div id="myDatacontainer">
//you can bind any propery of your data by using angular direvtives
//look at ng-bing, ng-if etc. directives
{{myData.name}} ...
</div>
</div>
Hope it help.
Consider you have following JSON data stored in a scope variable named data:
$scope.data = {
"array": [
1,
2,
3
],
"boolean": true,
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
Then you write your HTML in the following way like:
<div>
Boolean: {{data.boolean}}
</div>
<div>
Number: {{data.number * 2}}
</div>
<div>
Array:
<p ng-repeat="(key, value) in data.object"> {{key}} : {{value}}</p>
</div>
Another way to bind <div ng-bind="data.string"></div>
Here you can stop your call. You can use enhanced angular service $interval for this:
$scope.getData = function(){
var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
$http.get(url)
.success(function(data, status, headers, config) {
console.log(data);
$interval.cancel($scope.intervalObject); // cancel the interval when data is loaded
});
};
if (!$scope.data){
$scope.intervalObject = $interval($scope.getData, 2000);
}
if (!$scope.data){
setInterval($scope.getData, 2000);
}
since $scope.data is not set it'll continue calling the request(since you are not setting $scope.data anywhere).
Edit: Also, use angularjs $interval since it's the angular way of using setInterval and it keeps track of the $digest cycle

Categories