Some usages of angularJS
AngularJS is an excellent front-end JS framework that has been used in many Google products. AngularJS has many features, the most core of which are: MVC, modularization, automated two-way data binding, semantic tags, dependency injection, etc. This article mainly introduces some relevant information about the usage of angularJS. Friends who need it can refer to it. I hope it can help everyone.
AngularJS
##Event directive:
ng-click/dblclick ng-mousedown/up ng-mouseenter/leave ng-mousemove/over/out ng-keydown/up/press ng-focus/blur ng-submit
<button ng-click="clickFn($event)" class="btn btn-danger">aa</button>
##Form command
ng-change
It will be useful when the value changes
Some tags with value can only be used if they can be ng-model
Must be used with ng-model
can be used for data verification##
ng-disabled 控制元素是否可用 ng-readonly ng-checked
Only setting this can only control whether it is selected through data
Set ng-model and you can control the data through it
Form elements can be disabled by setting the disabled or readonly attributes. After disabled is set, users cannot use it. And the form will not submit this field, readonly
is only disabled by the user, that is to say, the user cannot operate, but the form will still be submittedCountdown to rush purchase small case$interval service is equivalent to setInterval, which can automatically check dirty data.
If you want to clear it, you need to assign a value and then $interval.cancel (timer)
var app = angular.module("myapp",[]) app.controller("myController",function ($scope,$interval) { $scope.num=1 $scope.canBuy = false $scope.time = 5 var timer = $interval(function () { $scope.time--; if($scope.time<=0){ $scope.canBuy=true $interval.cancel(timer) } },1000) })
There is a problem with ng-bind. After adding it, you cannot add anything else after the data variable. This tag can only Displaying this data, other data will not work, such as
{{name}}---111 用ng-bind-template就好 ng-bind-template="{{name}}---111"
ng-bind-html="<h1>{{name}}---111</h1>"
Then you need to hang the label to be displayed in a variable on, and then set it to ng-bind-html
$scope.text= "<h1>"+$scope.name+"---111</h1>" ng-bind-html=''text“ ng-non-bindable
<h3 ng-non-bindable>{{name}}</h3>
You can introduce an html code snippet, and you also need variables to define, and you can also write expressions in the code snippet
$scope.text='html/a.html'; ng-include='text'
ng-model-options='{updateOn:'blur'}'
ng-controller
<p ng-controller="myController as myFun"> {{name}}<br> {{myFun.age}}<br> {{myFun.sex}} </p> myapp.controller("myController",["$scope",myFun]) function myFun($scope){ $scope.name='allen'; this.sex='male' } myFun.prototype.age="18"
In angularJS, services are used to process data through certain functions
Interaction
$http({ url:"http://datainfo.duapp.com/shopdata/getclass.php", method:"get", params:{} }).success(function(data){ $scope.dataList=data; }).error(function(error){ console.log(error) })
The submitted data is equivalent to the data in $.ajax: {}
success success callbackerror error callbackHere we will talk about JSONP technologyJSONP is a common way to solve cross-domain problemsCross-domain problem: Because the browser has a same-origin policy, when different domains Cross-domain problems will occur when data are exchanged between them.
Same-origin policy: Data interaction can only be carried out under the same protocol, same domain name, and same port. Principle of JSONP: Yes The src attribute of the script tag (which uses a callback function to receive data) is not affected by the same-origin policy. You can request data from different domains and receive it by setting the callback function DataJSONP is a cross-domain method that combines front-end and back-end: because the front-end requests the data and needs to use it in the callback function, the back-end has to put the data back into the callback function
JSONP属于AJAX吗?ajax是指通过使用xmlhttprequest对象进行异步数据交互的技术,jsonp是依靠scriptsrc属性来获取的,不属于ajax
JSONP有什么缺点,使用的时候需要注意什么?
不能post跨域处理,需要注意的是:每次请求应该动态的创建script标签和回调函数,数据获取完成后销毁。
如果method是jsonp的话,就可以用jsonp去跨域请求,但是注意要在url后写关于callback的值为JSON_CALLBACK
百度搜索小例子
这里引用的是 angular-sanitize.js
var app = angular.module("myapp",['ngSanitize']) app.controller("myController",function ($scope,$http) { $http({ url:"http://datainfo.duapp.com/shopdata/getclass.php", method:"post", params:{a:1} }).success(function (results) { $scope.dataList = results }).error(function (error) { console.log(error) }) }) app.controller("yourController",function ($scope,$http) { $scope.search = function () { $http({ url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su", method:"jsonp", params:{ wd:$scope.wd, cb:'JSON_CALLBACK' } }).success(function (results) { $scope.dataList = results.s }) } })
$location服务
console.log($location.absUrl())//输出绝对地址 console.log($location.host())//输出域名 console.log($location.port())//输出端口 console.log($location.protocol())//协议 $location.path("aaa")//在路由中控制切换页面 console.log($location.path()) // #/aaa
$log 服务
多种控制台输出模式
$log.info("info"); $log.warn("warn"); $log.error("error"); $log.log("log");
angularJs对服务供应商配置
例如
myapp.config(["$interpolateProvider",function($interpolateProvider){ $interpolateProvider.startSymbol("!!"); $interpolateProvider.endSymbol("!!"); }])
angular就不认识{{}}了,开始变成!!!!
自定义服务 三种
1.factory
myapp.factory('serviceName',function(){ return .... })
可以return 字符串、数组、函数、对象(使用最多,最和逻辑)
引入方法和angualr自带的前面加$的服务完全一样,使用方法取决于return出来的是什么东西,自定义服务的服务名还是别加$了
eq:返回一个 两个数之间的随机数的服务
myapp.factory("myService",function(){ return { getRandom:function(a,b){ return Math.random()*(b-a)+a; } } })
自定义的服务可以依赖注入其他服务
myapp.factory('myHttpService',['$http',function($http){ return { $http({ url:...... }) } }])
eq:下一个自定义的http服务
myapp.factory("myHttpService",["$http",function($http){ return { http:function(url,sfn,efn){ $http({ url:url, method:"get" }).success(sfn).error(efn) } } }]) myHttpService.http("http://datainfo.duapp.com/shopdata/getclass.php",function(data){ console.log(data) },function(data){ console.log(data) })
2.provider
可以通过去自定义一个服务供应商去定义一个服务,写法有区别,服务功能性的东西需要嵌套一层返回
myapp. provider ('myHttpService',['$http',function($http){ return { $get:function(){ return:{//这里才是输出 } } }])
外面return出来的是这个服务的供应商,供应商的$get方法里返回的才是供我们使用的部分,可以通过更改供应商的部分参数来控制服务的功能,
eq:还是返回一个范围内的随机数,但是通过配置供应商的一个值来控制服务返回的是整数还是小数
myapp.provider("myService",function(){ return { isInt:true, $get:function(){ var that=this; return { getRandom:function(a,b){ var num=Math.random()*(b-a+1)+a; if(that.isInt){ return Math.floor(num); }else{ return(num) } } } } } }) myapp.config(["myServiceProvider",function(myServiceProvider){ myServiceProvider.isInt=false; }])
通过这种方法创建的服务是可以配置供应商的
3.service
通过这种方法创建出来的只能是对象
最简单的创建方式,自带返回,支持面向对象的写法
myapp.service("myService",function(){ this.getRandom=function(a,b){ return Math.random()*(b-a)+a; } }) myapp.service("myService",aaa) function aaa(){ this.getRandom=function(a,b){ return Math.random()*(b-a)+a; } }
多个控制器间数据的共享
实现多个控制器数据共享的方法有这样三种,
第一种比较简单,就是把数据放到父作用域上,就都可以访问了
第二种就是在控制器里通过$$prevSibling找到兄弟作用域,然后使用数据,需要注意的是,如果是初始数据类型的话就不能做数据双向绑定了
第三种是定义服务,把需要共享的数据做成服务,这样就都可以用了
<body> <p class="container"> <p ng-controller="firstController"> <input type="text" class="form-control" ng-model="name"> <input type="text" class="form-control" ng-model="data.name"> <input type="text" class="form-control" ng-model="Data.name"> <p> first-name:{{name}}<br> first-data-name:{{data.name}}<br> first-Data-name:{{Data.name}} </p> </p> <p ng-controller="secondController"> <p> second-name:{{name}}<br> second-data-name:{{data.name}}<br> second-Data-name:{{Data.name}} </p> </p> </p> </body> <script src="../Base/angular.min.js"></script> <script> var app=angular.module("myapp",[]); app.factory("Data",function () { return { name:'lily' } }) app.controller("firstController",function ($scope,Data) { $scope.name="allen"; $scope.data={ name:'tom' } $scope.Data=Data; }) app.controller("secondController",function ($scope,Data) { $scope.name=$scope.$$prevSibling.name; $scope.data=$scope.$$prevSibling.data; $scope.Data=Data; }) </script>
自定义模块
所有的模块都有服务,ng-app这个模块理由¥scope什么的服务,
咱们自己也可以写一个模块,然后里面可以去写服务
这样就可以把某些服务写在某个自定义的模块里,实现重复调用
例如把随机数的例子写在一个自定义的模块里
var myModule=angular.module("myModule",[]); myModule.service("myService",function(){ this.ran=function(a,b){ return Math.random()*(a+b)-a; } }) var myapp=angular.module("myapp",["myModule"]); myapp.controller("myController",["$scope","$log","myService",function($scope,$log,myService){ $log.log(myService.ran(5,10)) }])
其实像angualr.sanitize.js就是一个自定义模块
相关推荐:
The above is the detailed content of Some usages of angularJS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
