AngularJS doesn’t die, it just fades away
First, this article is about getting started with AngularJS, not Angular. Because ng(short for AngularJS) has been updated incompatibently since 2.x, and the syntax has been changed to Angular, learning NG is not the best choice in this era of changing front-end technology, but if your company uses it, Then there is no choice <_> this point in the domestic Baidu search volume can also be feltCopy the code
What about on a global scale
Of course, part of the popularity of Vue is vue, the software for editing videos. This heat is used as a reference Maybe you know ng developed by Google, and our vue author especially greatly was a Google engineer, may be contact in this regard So the initial vue on syntax is very similar and ng, vue shine on you, of course, to reduce the strangeness, so here I will compare some ng grammar and vue similarities, Easy to understandCopy the code
For example,
The ng-app=> directive defines an AngularJS application (specifying the root element). (VUE uses EL binding) ng-model => Bind the value of the input field to the application. (vue V-model) ng-bind => bind to HTML view (vue V-bind) ng-repeat => loop array (vue was v-repeat now v-for) Other custom directives such as. Directive, Add filters to expressions, etcCopy the code
Of course, there are a lot of differences. Ng is something closer to a framework, with its own routing, many services such as dependency injection, XHR, caching, URL routing, and browser abstraction. It uses the idea of dirty value detection to listen for data, whereas Vue uses data hijacking and observing subscriber patterns.
Without further ado, let’s explore NG
Introduction of depend on
< script SRC = "https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js" > < / script >
AngularJS is a JavaScript framework. One of the great things about AngularJS is that it extends HTML with multiple instructions, and we don’t have to manually manipulate the DOM as often as possible
Let’s start with a simple page
<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <script SRC = "https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js" > < / script > / / loaded AngularJS script < / head > < body > < div ng - app = "" > //ng-app represents a block of code inside the ng program <p> name: <h1>Hello {{name}}</h1> // The double curly bracket syntax displays the variables bound to the ng-model </div> </body> </html>Copy the code
A simple NG program is done
You may find this a bit strange, because in native JS we need to make our own event listener to do this
MVC is a model-view-controller design pattern. Simply put, NG uses the controller to keep the data model in sync with the view. When the model state changes, AngularJS immediately updates it in the view interface. And vice versa
Ng expression
Ng uses the double curly brace syntax **{{}}** to bind data to HTML
In addition to just binding one variable with {{name}}, we can also bind multiple variables {{name + age}}.Copy the code
Binding operator
<div ng-app="" ng-init="quantity=1; {{quantity * cost}}</p> //5 </div>Copy the code
You can also bind arrays, objects,
Ng instructions
We have already used the ng-model directive in the previous demo. If you have used vue, you may call the expert. Let’s use the expert several times
ng-repeat(v-for)
<div ng-app="myNg" ng-controller="myCtrl" > <ul> <li ng-repeat="x in name "> {{x}}</li> </ul> </div> </body> <script> Var app = angular.module('myNg',[]) app.controller('myCtrl',function($scope){$scope. Name = [1,2,3]}) </script>Copy the code
Now let's write the body code like this, and you can probably guess that this is a piece of code that goes through a set of numbers
Var app = angular.module(‘myNg’,[]) var app = new vue ({el: ‘#app’,}) it represents an AngularJS application defined by ng-app, which runs inside
Var app = new vue ({el: '#app', data:) var app = new vue ({el: '#app', data: { message: [1,2,3]}}) we define our variables in data and declare our variables in ng to our $scope. After version 1.6, we can also use other aliases such as vm instead of $scope. This is covered later. Why a model and controller, have $scope, the first model is used to declare our project, generally is unique, but in the normal development, we will have a lot of pages If we do not distinguish between scope is absolutely a disaster, so that we may have many a controller, the logic of the corresponding page. The $scope object calls the controller, which is essentially the application object of the controller through which you can call the controller's methodsCopy the code
Ng event
Ng-click ng-show ng-hide three commands that vUE developers may be familiar with and unfamiliar with
<div ng-show="false"></div> // do not show <div ng-ng="true"></div> // do not showCopy the code
Why do click events also use a command called ng-click? They listen for click events.
Can’T I use on-click? I really can’t
<div ng-app="myApp" ng-controller="siteCtrl"> <p >{{name}}</p> <button ng-click="click1()">ng-click</button> <button class="btn " >onclick</button> </div> <script> var app = angular.module('myApp', []).controller('siteCtrl', Function ($scope) {$scope.click1 = function(){$scope.click1 = $scope document.querySelector(".btn"); Btn.onclick = function () {$scope.name = 'red '; }; });Copy the code
As you can see, the onclick listening method is not working here. Because ng uses the method of dirty value detection for data, you can understand it as a large listener. In consideration of performance, it limits the listening particles. Therefore, if we want to use onclick, we can manually trigger dirty value detection by adding scope.scope.scope.apply() after changing data
Filter filter
Filter is very useful, ng filter built-in many, of course you can also define their own
The < body > < div ng - app = "myApp" ng - controller = "personCtrl" > < p > name for {{lastName | uppercase}} < / p > < input type = "text" ng-model="lastName"> </div> </body> <script> angular.module('myApp',[]).controller('personCtrl',function($scope){ }) </script>Copy the code
< p > {{lastName | uppercase}} < / p > this is the filter method (|) is called in the ng pipeline characters, on the left is my our variables, on the right is our filter. I'm using a built-in lower-case to upper-case filter here
I brought these with me
- Currency Formats a number into a currency format.
- The lowercase format string is lowercase.
- Order Derby arranges an array based on an expression.
- Uppercase Formats the string in uppercase.
< p > < input type = "text" ng - model = "test" > < / p > < li ng - repeat = "names in x | filter: test | orderBy: 'a value of x" > {{(x.n ame | Uppercase) + ', '+ x.ountry}} </li> this means that only the values of the ng-model binding are displayed, arranged in orderBy the values in order DerbyCopy the code
We can also write one that we need
<body > <div ng-app="myApp" ng-controller="personCtrl"> <p> {{ name | double }}</p> <input type="text" ng-model="name"> </div> </body> <script> var app = angular.module('myApp',[]).controller('personCtrl',function($scope){ $scope.name = '' }) app.filter('double', function() { return function(text) { return text+","+text; }}); </script>Copy the code
AngularJS services (Service)
The name “service” is confusing, but it can actually be interpreted as ng providing us with a way to use some common class libraries.
Traditionally, we would define some global methods, or introduce methods in other files. There are more than 30 built-in services, such as $setTimeout,$location,$HTTP. Their functions can be seen from the name. When we use them, we need to inject them into our controller. My understanding is that NG has made appropriate enhancements to these methods on the one hand, and improved performance by using just-injected methods on the otherCopy the code
Let’s take $HTTP and see how it works
We a few data, his first in the data. The json in {" sites ": [{" Name" : "Shanghai"}, {" Name ":" tap water "}, {" Name ":" from "}, {" Name ":" the sea "}]}Copy the code
$HTTP is passed as a parameter to the controller. If it is used by a self-defined service, it needs to be defined in controller
var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { $http.get("./data.json") .then(function (response) {$scope.names = response.data.sites; }); });Copy the code
The code is very simple, because here ng help us to encapsulate the request header parameters, for simple requests we can call directly, but if you are directly opened in your computer to see the effect, may report a cross-domain errorCopy the code
I'm using vscode for the compiler here, you can download oneCopy the code
Of course, there are three types of services, as well as custom services, but those are not the original intention of this article I just briefly introduced here, if there is a need to search for yourselfCopy the code
routing
If a single page application doesn’t support routing, like a bookstore doesn’t sell books, what does ng routing look like
In ordinary websites, every time we enter a web page, we need to refresh and obtain the content of the server side, which will bring bad user experience to users. However, the page content of routing control is only a mapping of local content, which is a switch between paths, that is, the switch of components. We usually visit the web page is this format: http://someweb.com/home in ng, the content of the specific page with #! Tag implementation if it is the above web page, that is http://runoob.com/#! /homeCopy the code
See the NG routing tutorial here for details
Writing here, it seems to be a bit of the flavor of the title party. In fact, the original intention of this article is because WHEN I was learning NG, I found that there was no particularly suitable introductory tutorial. The tutorials I saw were also full of sense of time, so I would have the emotion at the beginning of the article
Reference documentation
Novice tutorial
Details vm and $scope
The usage of the ng instruction