Tag Archives: AngularJs

Data-binding in AngularJs

There are two types of data-binding in AngularJs:

1. One-Way Binding/ Basic Data-Binding

2. Two-way Binding

One-Way Binding:

A data binding can be specified in two different ways:

  • with curly braces: {{expression}}
  • with the ng-bind directive: ng-bind=“varName”

Example to show one-way binding:

HTML page(View):

<!DOCTYPE html>
<html>
<head>
<script src=”angular.js”></script>
</head>

<body ng-app ng-init=”firstName = ‘Daniel'; lastName = ‘Smith';”>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind=”lastName”></span>
</body>
</html>

We’re saying one way data binding because the model values (here the variables represent the model) are automatically assigned to the HTML placeholder elements specified through the data binding notation, but the HTML elements don’t change the values in the model (one way).

Two-way data binding:

We have a two way data binding when a model variable is bound to a HTML element that can both change and display the value of the variable. In general, we could have more than one HTML element bound to the same variable. We use the ng-model directive to bind a model variable to the HTML element that can not only display its value, but also change it.

<!DOCTYPE html>
<html>
<head>
<script src=”angular.js”></script>
</head>

<body ng-app ng-init=”firstName = ‘Daniel'; lastName = ‘Smith';”>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind=”lastName”></span><br />
<br />
<label>Set the first name: <input type=”text” ng-model=”firstName”/></label><br />
<label>Set the last name: <input type=”text” ng-model=”lastName”/></label>
</body>
</html>

In the example, we bind the firstName and lastName model variables to a couple of HTML input elements. When the page is loaded, the value of the input elements are initialized to those of the respective model variables and whenever the user types something in an input, the value of the model variable is modified as well (two way).


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

 

 

How to redirect to home route when no route is defined?

In AngularJs, $routeProvider is used for configuring routes.

Requires the ngRoute module to be installed.

when(path, route);

Adds a new route definition to the $route service.

$routeProvider.when(‘/index’, { templateUrl: ‘/view/project.html’, controller: ‘projectController’ });

You can use,

otherwise(params)

Sets route definition that will be used on route change when no other route definition is matched.

.otherwise({ redirectTo: ‘/Home’ });

To redirect to home page when no other route is provided.


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

 

 

 

Dynamic URL’s in angularJs

Dynamic URL’s in AngularJs:

To have dynamic URL’s in AngularJs you need to include             angular-route.js.

Then, you can use following code snippet to dynamically redirect URLs:

angular.module(‘myapp’,[]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: '/menu/Noodle.html', controller: HomeController });
$routeProvider.when('/about', { templateUrl: '/pages/about.html', controller: AboutController });
$routeProvider.when('/privacy', { templateUrl: '/pages/privacy.html', controller: AboutController });
$routeProvider.when('/terms', { templateUrl: '/pages/terms.html', controller: AboutController });
$routeProvider.otherwise({ redirectTo: '/' });
}]);

You can change URLs according to your requirements.


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

 

AngularJs Routes

AngularJS routes enable you to create different URLs for different content in your application. A route is specified in the URL after the # sign.

As shown below:

http://angularjsapp.com/index.html#users

When browser loads application it bydefault goes to index.html but angularJs looks at routes and decides which template to show.

Routing in AngularJs:

1. Include AngularJs Route Module:

We need to include AngularJs Route Module if routing is to be done.

<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js”></script>

2. Declare dependency on Route Module:

Application needs to declare dependency on route module in order to use ngRoute module.

var module = angular.module(“sampleApp”, ['ngRoute']);

3.  ngView Directive:

Use ngView inside <div>, so that template specific to route will be displayed here.

<div ng-view></div>

4. Configure $routeProvider:

The $routeProvider is what creates the $route service. By configuring the$routeProvider before the $route service is created we can set what routes should result in what HTML templates being displayed. As shown below:

module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: 'template-1.jsp',
controller: 'UserController'
}).
otherwise({
redirectTo: '/'
});
}]);

The when() function takes a route path and a JavaScript object as parameters.

The otherwise() function takes a JavaScript object. It tells AngularJS what it should do if no route paths matches the given URL.

5. Provide Links to Routes:

Provide links to route as shown below :

<a href=”#/route1“>Route 1</a><br/>

6. Route paramenters:

We can provide parameters with routes path as shown:

#/users/1

Here, ‘1’ is the parameter passed with route path.

We can read parameters while configuring $routeProvider as shown below:

when(‘/route1/:param‘, {
templateUrl: ‘template-1.jsp’,
controller: ‘RouteController’
})

Controller can get access to params using $routeParams service as shown below:

module.controller(“UserController”, function($scope, $routeParams) {
$scope.param = $routeParams.param;
})

Now, your view can also get access to param as $scope.param is assigned the value of $routeParams.param.


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

 

 

 

 

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.