Angularjs Getting Started

Source: Internet
Author: User

What is Angularjs?

Angularjs is a front-end JavaScript framework with Google support behind it. The framework was first released in 09 and subsequently developed rapidly, especially recently, with high prevalence. Unlike other frameworks, Angularjs has a number of unique features that make it very different. Considering my article to write more logical confusion, if you do not understand ANGULARJS, recommend you first go to its [official website] (http://www.angularjs.org) look. For me, the two features that attracted me the most were two-way binding and dependency injection. The former eliminates the refresh Dom shown during development, allowing developers to focus more logically, while the latter makes testing and integration very convenient.

# # # Hello,world # #
First look at a classic Hello world.

123456789101112131415161718192021 <html><head><scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script><script>function HelloController($scope) {    $scope.person = {    name: "World"}$scope.sayHelloWorld = function() {    alert($scope.person.name);}</script></head><bodyng-app><divng-controller="HelloController">    <inputtype="text" ng-model="person.name" />    <buttonng-click="sayHelloWorld()"></button></div></body></html>

  

# # # Controller # #
In angular, the controller is primarily responsible for initializing the scope, including the data and required functions. The Hellocontroller above is a typical controller, and another more powerful way of defining it is to allow you to declare the modules you depend on.

12345678910 varcontrollers = angular.module(‘demo.controllers‘);controllers.controller("demoController", [‘$scope‘‘$http‘function($scope, $http) {    $scope.test_data = {        value: ‘test data‘    };    $scope.test_function = function() {        alert("test function");    };}]);

  

Controller more intuitive, need to note that there are two places, one is to use $watch to pay attention to the value of an expression, when the change occurs when the corresponding operation, the second is the use of external library operation data, you need to use the Apply notice angular, otherwise it is likely that the external library updated data, But angular did not update it accordingly.

# # # Directive # #
In front-end development, it is often necessary to manipulate the DOM, and sometimes it takes a lot of HTML to build a common component, such as a piece of information in the Google + stream, which is directive in angular. This also means that manipulating the DOM in a controller is a mistake.

Typically, the directive definition is named with the CamelCase rule, and is separated using a horizontal line when used.

Definition of Directive

123456789101112131415161718192021222324 var directives = angular.module(‘demo.directives‘, []);directives.directive(‘customDirective‘function() {return{     restrict: ‘ECMA‘,     template: ‘<nav></nav>‘,     templateUrl: ‘directive.html‘,     replace: false,     priority: 0,    transclude: false,    scope: false,    terminal: false,     require: false,    controller: function(scope, element, attrs, transclude, otherInjectables {},    compile: function(element, attrs, transclude) {        return{            pre: functionpreLink(scope, element, attrs, controller) {},            post: functionpostLink(scope, element, attrs, controller) {}       };    },    link: function(scope, element, attrs) {    }};});

  

Restrict: Specifies the use of the directive, a total of four kinds:
1. Element (e when restrict is defined)
2. Attribute (a when restrict defined)
3. Class (c when restrict is defined)
4. Comment (m as defined by restrict)

Compile: In directive, if the DOM element needs to be processed, it is basically done in this function. Looking closely at this function, compile does not have access to scope,
Link: The main function of this function is to do data binding to the DOM and scope. Unlike compile, in this function, you can already access scope.
Templates and Templateurl: Used to specify the template for directive, which directly uses a string to define the template, while the latter links the external template file via a URL. The scope in the corresponding controller or rootscope can be used in the template, with the exception of course, see the explanation about scope.
Replace: Specifies whether to use a template to replace a DOM element that directive.
Priority: Specifies priorities, angular, when processing directive, all directive that appear on the page are sorted by priority, generally this value is unspecified. The controller that corresponds to the
Controller:directive is typically used for communication between directive. In this function, all the variables that are bound to this, and the other directive can be accessed by using require.
require: accesses its corresponding controller by specifying the name of a directive. Which of the? As a prefix, if you cannot find this directive will error, and the ^ prefix, will be in the parent element recursive lookup, you can use the array to introduce multiple directive, such as [' directive1 ', ' directive2 ', ' directive3 ']
Scope: Used to specify the scope of the current directive, and the impact between the different values is very large.

1. False: Directive share scope with parent element at this time
2. True: At this point directive has its own scope, which inherits the scope of the parent element
3. Isolate:directive has its own scope, which does not inherit from the scope of the parent element, but can still pass scope. $parent access to the scope of the parent node. This is not a recommended practice because it restricts the parent element and affects the scope of the directive. If you want to share data between parent and child elements, you can explicitly specify that those elements need to be shared between parent and child. There are three types of methods:
Use @ To bind the attributes in the parent scope to the local scope, one-way binding, which is always a string, and you need to use the {{}} in the template
Use = Ibid, except here is a two-way binding, in the template can directly give the parent scope of the property name
Use & to pour a function or an expression

Transclude: Used to control whether the child element of the directive is to be added to the template ng-tranclude the specified element

# # # Service # #
In angular, the service is a few singleton objects that provide common functionality. such as the appearance of $http, and so on, its use is relatively simple, as long as the use of the declaration of this dependency can be, such as the above Democontroller. There are several main ways to define it:
1. Service is simply a value can be registered using constant (name,value), if the object already exists, you can use value (name,value) to register

1234567891011 varservices = angular.moudle(‘demo.services‘, []);services.constant(‘number‘, 42);services.constant(‘string‘‘string‘);varexistingService = {    notify: function(msg) {        alert(msg);    }};services.value(‘notify‘, existingService);

  

2. Register a service constructor

1234 services.service(‘demoService2‘function() {    this.func = function() {    };});

  

3. Register a factory function to create a service instance, which you can do before creating the services instance

1234567 services.factory(‘demoService1‘function(msg) {    // some processing code    return{        func: function() {        }    };});

  

4. Using provider, this approach is a bit more complex, but the benefit is that the service can be configured.

123456789101112131415 services.provider(‘demoService3‘function() {    this.value = "string";    this.$get = function() {       varvalue = this.value;        return{            print: function() {                console.log(value);            }        }    }     this.setValue = function(value) {        this.value = value;    }});

  

Config can be used to configure the provider

123 services.config(function(demoService3Provider) {    demoServiceProder.setValue(‘hello‘);});

  

Of course, the creation of services can also be declared dependent, the specific format and controller similar, no longer verbose.

Angular also has a lot of concepts, including router and filter, which I seldom use and have not studied in detail.

Angularjs Getting Started

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.