ANGULARJS Learning Registration Services Custom Directives

Source: Internet
Author: User
Tags bind

ANGULARJS Registration Service

Angularjs's background control can be implemented in controller. But if all the logic code is written to controller it will appear that the controller is too bloated. Inconvenient Maintenance, ANGULARJS provides a way to rely on injection. We can encapsulate the logic processing into the service and need to invoke the corresponding service only.

Angular offers 3 ways to create and register our own service.

1.Factory

2.Service

3.Provider

I. Factory:

1. A myfactory is built below to set up personal information and to display personal information.

Note:1. You must call return in there or you will get an error.

2. All accessible methods are placed in the service.


App.factory (' MyFactory ', function () {

var service = {};
var _name = ';
var _age = ';

Service. SetInfo = function (name,age) {
_name = name;
_age = age;
}

Service. Showinfo = function () {
Return _name+ ': ' +_age;
}

return service;
});



2. Services can be registered in controller through function (myfactory). The console will print out the frank:23

var app = Angular.module (' MyApp ')
App.controller (' Injectctrl ', function ($scope, myfactory) {
Myfactory.setinfo (' Frank ', 23);
Console.log (Myfactory.showinfo ());
});

two. Service

1. Service is similar to factory usage, except that you do not need to return an object.


var app = Angular.module (' MyApp ')

App.controller (' Injectctrl ', function ($scope, MyService) {
Myservice.setinfo (' Frank ', 23);
Console.log (Myservice.showinfo ())
});

App.service (' MyService ', function () {
var _name = ';
var _age = ';

This. SetInfo = function (name,age) {
_name = name;
_age = age;
}

This. Showinfo = function () {
Return _name+ ': ' +_age;
}
});



three. Provider:

1. Provider: To achieve the return of data through the #get method.


App.provider (' MyProvider ', function () {

var service = {};
var _name = ';
var _age = ';

Service. SetInfo = function (name,age) {
_name = name;
_age = age;
}

Service. Showinfo = function () {
Return _name+ ': ' +_age;
}

this. $get = function () {
return service;
}
});



Angularjs Custom Directives


In the front-end development, we will encounter many places will use the same type of control. ANGULARJS provides custom instruction functionality, and we can define specific HTML templates in the instructions. provided to the foreground HTML call.

a simple definition of a directive .

A simple control is defined below and is clicked back to the blog park.

Note:1. Naming: directive must begin with a lowercase letter, which, if followed by a capital letter, is called by the HTML call-separating the words.

<script src= ' angular.js ' ></script>
<script type= "Text/javascript" >
Angular.module (' MyApp ', [])
. directive (' Mycnblogs ', function () {
return {
Restrict: ' E ',
Replace:false,
Template: ' <a href= ' http://www.cnblogs.com/' >go to Cnblogs</a> '
}
})
</script>
<title></title>
<div ng-app= ' MyApp ' >
<my-Cnblogs></my-Cnblogs>
</div>
<body>
</body>

two. Introduction to instruction elements:

2.1 Restrict

Commonly used restrict have e,a,c three kinds of settings. These settings can be mixed, such as Ea,ac. Do not need to be separated by symbols

E (Element): elements, using the format is <my-directive></my-directive>

A (propertity): Properties, using format: <div my-directive></div>

C (Class): class, using format: <div class= ' my-directive ' ></div>

2.2 Repleace

The following are the effects of replace set false and True respectively




2.3 Termplate:

Template is to set the corresponding HTML template, if you have HTML wrapping, you should add/sign at the end of each sentence. If you have more HTML code, you can load the appropriate code template by setting the Templateurl:urlpath

three. Add data to the instruction

3.1 The following is a simple implementation of data binding by setting scope.

<! DOCTYPE html>
<script src= ' angular.js ' ></script>
<script type= "Text/javascript" >
Angular.module (' MyApp ', [])
. directive (' mydirective ', function () {
return {
Restrict: ' A ',
Replace:true,
scope:{
Myurl: "@",
Mycontent: "@"
},
Template: ' <a href= ' {{myurl}} ' >{{mycontent}}</a> '
};
});
</script>
<title></title>
<div ng-app= ' MyApp ' >
<div my-directive myurl= ' http://www.cnblogs.com/' mycontent= ' Go to blogs ' ></div>
</div>
<body>
</body>


3.2 Deep understanding of the bindings of the custom control scope

Custom control bindings $scope are divided into @,=,& three cases. Personally think @: one-way binding, =: bidirectional binding, and: for binding functions, see below Angularjs authoritative guide introduction

@ Local Scope Properties: Use the @ symbol to bind the local scope to the value of the DOM property.

= bi-directional binding: by = You can bind properties on the local scope's attributes on the parent-child scope to two-way data binding. As with normal data binding, local properties reflect the changes that occur in the parent data model

& Parent Scope bindings can bind a parent scope to run a function through the & symbol. means that when you set this value, a wrapper function that points to the parent scope is generated.

The following demo implements the binding of three scenarios.


<! DOCTYPE html>
<script src= ' angular.js ' ></script>
<script type= "Text/javascript" >
Angular.module ("myApp", [])
. directive ("Mydir", function () {
return {
Restrict: "A",
Scope: {
Name: "@",
Desc: "=",
Show: "&"
},
Template
"<div>" +
"<input type= ' text ' ng-model= ' name '/>: <input ng-model= ' desc '/> ' +
"<button ng-click= ' show () ' >show</button>" +
"</div>",
Replace:true,
Link:function (scope, element, Attrs) {
Console.log ("Initial value for Name:" + scope.name);
Console.log ("Initial value for Description:" + scope.amount);
Scope. $watch ("desc", Function (newval, oldval) {
Console.log ("desc has changed" + Oldval + ">>" + newval);
});
Scope. $watch ("name", function (newval, oldval) {
Console.log ("name has changed" + Oldval + ">>" + newval);
});
}
}
})
. Controller ("Myctrl", function ($scope) {
$scope. CustomerName = "Frank";
$scope. Content = ' Learning angular ';
$scope. Show = function (source) {
alert (source);
};
})

</script>
<meta charset= "Utf-8"/>
<title></title>
<body ng-app= "myApp" ng-controller= "Myctrl" >

<input type= "text" ng-model= ' customerName ': <input ng-model= "Content"/>
<button ng-click= "Show (' normal function ')" >show</button>

<div My-dir
Name= ' {{customerName}} '
desc= "Content"
Show= "Show (' custom directive binding function ')" >
</div>
</body>

Here is the effect chart:



Four. Summary:

This chapter introduces the simplicity and practicality of custom directives. You can encapsulate HTML templates for a number of specific features through custom directives for page calls. You can try to change the above demo & to @ or =, after the test modified to the @ symbol, the custom directive's Show method is unable to execute. It would be interesting to change to the = number. Click on the btn above to execute the Show method two times. Then modify any of the input, the following show method will be executed. If you have Bo friends know what the reason also please reply online. This principle is really not clear what is the reason.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.