How to make Ajax call with $http service in AngularJs?

In AngularJS you can send AJAX requests in several different ways.Following are the ways :

1. AJAX calls via the $http service

2. JSONP calls via the $http service

3. REST type calls

The $http service:

The $http service is the easiest way to send AJAX calls.

$http functions:

  • $http.get(url, config)
  • $http.post(url, data, config)
  • $http.put(url, data, config)
  • $http.delete(url, config)
  • $http.head(url, config)

Parameter ‘data’ is send to server.The data parameter will be converted to a JSON string.

Example:

To make AJAX call you can use ng-click ,

<button ng-click=”myData.doClick(item, $event)”>Send AJAX Request</button>

write your method in <script> tag.

angular.module(“myapp”, [])
.controller(“MyController”, function($scope, $http) {
$scope.myData = {};
$scope.myData.doClick = function(item, event) {

var responsePromise = $http.get(“/angularjs-examples/json-test-data.jsp”);

responsePromise.success(function(data, status, headers, config) {
$scope.myData.fromServer = data.title;
});
responsePromise.error(function(data, status, headers, config) {
alert(“AJAX failed!”);
});
}

} );

The the $http.get() function returns a “promise” object. This promise object has a success() and an error() function. By calling these functions and pass a function to them as parameter you can control what happens when the AJAX call finishes.


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

 

How to write custom directives in AngularJs?

AngularJs directives controls how HTML is rendered into AngularJs Application. There are  already available directives in angularJs but if you need, can create your own directives.

Custom Directives in AngularJs can be created as shown in following steps:

You will need to register your directive with module

myapp = angular.module(“myapp”, []);

myapp.directive(‘userDetails’, function() {
var directive = {};

return directive;

});

First parameter in directive() is the name of directive. In the above example ‘userDetails‘ is the name of custom directive.Whenever you use ‘userDetails‘ in HTML template it will activate directive.

Second parameter is factory function. This function should return a directive definition when invoked. AngularJS will invoke this function to obtain a JavaScript object which contains the definition of the directive.

The restrict field is used to set if the directive should be activated by a matching HTML element, or an element attribute. By setting restrict to E you specify that only HTML elements named ‘userDetails' should activate the directive. By setting restrict to A you specify that only HTML attributes named ‘userDetails' should activate the directive. You can also use a value of AE which will match both HTML element names and attribute names.

myapp.directive(‘userDetails’, function() {
var directive = {};

directive.restrict = ‘E';

return directive;

});

There is Template field which will replace the content of directive with specified template.

If we add Template field in directive, as shown below:

myapp.directive(‘userDetails’, function() {
var directive = {};

directive.template = “My first directive: {{textToInsert}}”;

return directive;
});

In your HTML page, if you use <userDetails>

<div ng-controller=”MyController” >
       <userDetails>This will be replaced</userDetails>
</div>

You can give templateUrl to be uploaded to replace content of your directive. As shown below:

myapp.directive(‘div’, function() {
var directive = {};

directive.restrict = ‘E'; /* restrict this directive to elements */

directive.templateUrl = “/myapp/templates/showUserDetail.html”;

return directive;
});

AngularJs will upload template from URL given.


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

AngularJs Templates

Templates are one of important feature that angularJs provides.

Here, templates are nothing but plain-old-html file with added instrctions on how model should be rendered on view.

This templates are parsed by browser into DOM. Then , this DOM becomes input for AngularJs compiler. AngularJS traverses the DOM template for rendering instructions, which are called directives.

The input to AngularJS is browser DOM and not an HTML string.Using the DOM as the input, rather than strings, is the biggest differentiation AngularJS has from its sibling frameworks.

Example shown below:

function UserController($scope) {
scope.images = [
{"name":"user1"},
{"name":"user2"},
{"name":"user3"}

];
}

<div ng-controller=”UserController”>
<ul>
<li ng-repeat=”user in users”>
<img ng-src=”{{user.name}}” >
</li>
</ul>
</div>


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

How to create Custom Filters in AngularJs?

Creating custom filter is simple in AngularJs. You just need to create controller and then create filter.

For declaring controller do as following,

app.controller(‘myCtrl’, function(){});

For creating filter append following to your Angular application,

.filter(‘filterName’, function(){});

Example of filter to find which languages are static:

var app = angular.module(‘filters’, []);

app.controller(‘demo’, function($scope){
$scope.example1 = [
{name: 'C#', type : 'static'},
{name: 'PHP', type : 'dynamic'},
{name: 'Go', type : 'static'},
{name: 'Rust', type: 'static'}
]
})

app.filter(‘staticLanguage‘, function(){
return function(input){
var out = [];
angular.forEach(input, function(language){
if(language.type === ‘static’){
out.push(language)
}
})
return out;
}
})

In your View to apply filter write following:

<li ng-repeat=”lang in example1 | staticLanguage“>{{lang.name}}</li>


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

 

 

How to share data between controllers in AngularJs?

To share data between controllers in AngularJs we have to states.

For using states, we need to include angular-ui-router in your application.

<script src=”//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.js”></script>

To use ui-router we need to create dependency on ui-router.

angular.module(“app”,["ui.router"])

Then create states for your controllers as shown below:

.config(function config($stateProvider){

$stateProvider.state(“index”,{

url:”/yourUrl”,

controller:”firstController as first”,

templateUrl:”template_url”

})

$stateProvider.state(“second”,{

url:”/yourSecondPageUrl”,

controller:”secondController as second”,

templateUrl:”template_url”

})

})

Then write service to pass data in both controllers as parameter.

.service(“data”, function  shareData(){

var data = this;

data = “data_to_transfer”

})

.controller(“firstController”, function(data){

var first = this;

first.data = data;

})

same for secondController.

Now, in your view you can access it as {{first.data}} and likewise for secondcontroller.

To redirect to new state use

<div ui-sref=”second”>Go to second page</div>


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

 

 

 

How to include external libraries by requiring modules in node.js?

To include external libraries in Java, we use import statement.

In node.js, we use require keyword. For example,

var http = require(‘http’);

We can also include relative files as shown below:

var myFile = require(‘./myFile’); // loads myFile.js

To install modules from npm(node package manager),

$ npm install express

Modules aren’t automatically injected into the global scope, but instead you just assigned them to a variable of your choice.

 

You can create your own module as well.

  •  The first approach would be to export a single object:

        var person = { name: ‘John’, age: 20 };

        module.exports = person;

  • The second approach requires adding properties to the exports object:

     exports.name = ‘John';
       exports.age = 20;

Modules don’t share scope, so if you want to share a variable between different modules, you must include it into a separate module that is then required by the other modules. And also modules are loaded once and then are cached by node.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

 

 

How to handle errors in Node.js?

Error Handling is important in any of the language. If you don’t handle errors, then your program may crash or go to inconsistent state.

In Node, we have Error-first callback as the  standard protocol for callbacks. This is very simple convention with only one rule, the first argument for the callback function should be the error object.

That is there are following two scenarios:

1. Your Error argument is null, then your program is without error.

2.  Your Error argument is not null, then you need to handle error.

Example of Error-first callback:

fs.readFile(‘/foo.txt’, function(err, data) {
// …
});

Here, readFile has two parameters error and file data.

To handle err, you just need to put a check for getting value of err.

If( err ){
console.log(err);
}else{
console.log(“working fine”);
}

EventEmitter errors:

When working with event emitters , you should be careful. If there’s an unhandled error event it will crash our application.

Example of eventEmitter:

var EventEmitter = require(‘events’).EventEmitter;
var emitter = new EventEmitter();
emitter.emit(‘error’, new Error(‘something bad happened’));

You can handle event emitter errors as shown below:

emitter.on(‘error’, function(err) { console.error(‘something went wrong with the ee:’ + err.message); });

Propagating more descriptive errors with the verror module:

There are some situations where we don’t handle errors ourselves. We just delegate it to callback.In above way of handling errors, we don’t get exact stack trace.

In real world applications, there will probably be a function that calls another function that calls the original function. So, to know from where exactly error came.

For this Node has verror module, which we have to integrate with the application.With verror, we can wrap our errors to provide more descriptive messages.

We will have to require the module at the beginning of the file and then wrap the error when invoking the callback:

var verror = require(‘verror’);
function readFiles(files, callback) { …
return callback(new VError(err, ‘failed to read file %s’, filePath));

}

 


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

 

How to access MySql database with Node?

In Node, everything goes with modules i.e., download and install module. For accessing MySql , we have module mysql@2.0.0-alpha2.

Steps to access MySql  with Node:

1. Install module:

npm install mysql@2.0.0-alpha2

This will download and install module for mysql.

2. Using module in your application:

var http = require(‘http’),
// And mysql module you’ve just installed.
mysql = require(“mysql”);

// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
user: “root”,
password: “”,
database: “db_name”
});

// Create the http server.
http.createServer(function (request, response) {
// Attach listener on end event.
request.on(‘end’, function () {
// Query the database.
connection.query(‘SELECT * FROM your_table;’, function (error, rows, fields) {
response.writeHead(200, {
‘Content-Type': ‘x-application/json’
});
// Send data as JSON string.
// Rows variable holds the result of the query.
response.end(JSON.stringify(rows));
});
});
// Listen on the 8080 port.
}).listen(8080);

Querying with this library is easy as we just need to write query and a callback function.

3. Save this file as mysql.js and run it as

$node mysql.js

4. Then navigate to http://localhost:8080 in your browser, and you should be prompted to download the JSON-formatted file.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

How to read and write files in Node.js?

To manage files in Node, we use the fs module (a core module). We read and write files using the fs.readFile() and fs.writeFile() methods, respectively.

Steps to read and write files are shown below:

// Include http module,
var http = require(“http”),
fs = require(“fs”);

// Create the http server.

http.createServer(function (request, response) {
// Attach listener on end event.
request.on(‘end’, function () {
// Check if user requests /
if (request.url == ‘/’) {
// Read the file.
fs.readFile(‘test.txt’, ‘utf-8′, function (error, data) {
// Write headers.
response.writeHead(200, {
‘Content-Type': ‘text/plain’
});
// Increment the number obtained from file.
data = parseInt(data) + 1;
// Write incremented number to file.
fs.writeFile(‘test.txt’, data);
// End response with some nice message.
response.end(‘This page was refreshed ‘ + data + ‘ times!’);
});
} else {
// Indicate that requested file was not found.
response.writeHead(404);
// And end request without sending any data.
response.end();
}
});
// Listen on the 8080 port.
}).listen(8080);

This code demonstrates the fs.readFile() and fs.writeFile() methods. Every time the server receives a request, the script reads a number from the file, increments the number, and writes the new number to the file. The fs.readFile()method accepts three arguments: the name of file to read, the expected encoding, and the callback function.

Save this as files.js. Before you run this script, create a file named test.txt in the same directory as files.js.

Run application as $node file.js


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

Debugging Node applications

For debugging in Node, we have node-inspector module available.

To install node-inspector write following:

npm install -g node-inspector

To run your application with node-inspector,

# basically `node-debug` instead of `node`
$ node-debug example.js

where example.js is name of your application.

That should start our application and open the node-inspector interface in Chrome.  Then setup breakpoint in request handler click on line from where you want to start debugging code. Then visit to localhost in new tab.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.