search
HomeWeb Front-endJS TutorialHow to use it in angularJS?

How to use it in angularJS?

Jun 23, 2018 pm 04:38 PM
angularjsusage

This article mainly introduces some related information about the usage of angularJS. Friends who need it can refer to it

AngularJS

Event instructions:

ng-click/dblclick
ng-mousedown/up
ng-mouseenter/leave
ng-mousemove/over/out
ng-keydown/up/press
ng-focus/blur
ng-submit

Same as ng-click, both bind events to the dom

It should be noted that using event objects Sometimes, you need to pass in $event in commands such as ng-click, such as:

<button ng-click="clickFn($event)" class="btn btn-danger">aa</button>

Form command

ng-change

When the value changes Sometimes it will be useful

Some tags with value can only be used if they can be ng-model

Must be used with ng-model

Can do data verification

ng-disabled 控制元素是否可用
ng-readonly
ng-checked

Control whether the checkbox is selected

Only setting this can only control whether it is selected through data

Set ng- The model can control the data through it

The difference between disabled and readonly

Form elements can be disabled by setting the disabled or readonly attributes , after disabled is set, the user cannot use it, and the form will not submit the field. readonly

is only disabled by the user, that is, the user cannot operate, but the form will still be submitted

Countdown to rush purchase small case

$interval service is equivalent to setInterval, which can automatically perform dirty data inspection

If you want to clear it, you need to assign a value and then $interval.cancel (timer)

ng-show is displayed as true. false hide

ng-hide is true to hide. false display

ng-if is the same as ng-show, except that if it is not displayed, the node is not in the dom document

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)
 })

ng-bind related

ng-bind has a problem. After adding it, you cannot add other things after the data variable. This tag can only display this piece of data, but not others. For example

{{name}}---111
用ng-bind-template就好
ng-bind-template="{{name}}---111"

There is another problem, the tag cannot be parsed

It’s okay, use ng-bind-html

ng-bind-html="<h1 id="name">{{name}}---111</h1>"

This will not work, this is before 1.3, it will be bigger after 1.3 During the change, in order to streamline angular.js, we removed this thing. We had to use a plug-in (module)

and we had to put "ngSanitize" in angular.module

Then you need to hang the label to be displayed on a variable, and then set it to ng-bind-html

$scope.text= "<h1 id="scope-name">"+$scope.name+"---111</h1>"
ng-bind-html=&#39;&#39;text“
ng-non-bindable

This command can prevent the expression from being parsed

<h3 id="name">{{name}}</h3>

ng -include

You can introduce an html code snippet, and you also need variables to be defined. You can also write expressions in the code snippet.

$scope.text=&#39;html/a.html&#39;;
ng-include=&#39;text&#39;

Pay attention, because it is actually ajax inside Requested, so it needs to be in a server environment

ng-model-options=&#39;{updateOn:&#39;blur&#39;}&#39;

During the display process of bound data, the node will be operated internally, and the performance is not good. You can configure it like this, and update the data displayed in the view at a certain moment. ok

AngularJS

ng-controller

You can use object-oriented thinking to write 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=&#39;allen&#39;;
 this.sex=&#39;male&#39;
}
myFun.prototype.age="18"

Let’s talk about services. Services are actually already A lot has been said.

In angularJS, services are used to interact with data through certain functions

$http service

#

$http({
 url:"http://datainfo.duapp.com/shopdata/getclass.php",
 method:"get",
 params:{}
}).success(function(data){
 $scope.dataList=data;
}).error(function(error){
 console.log(error)
})

method represents the delivery method get, post

url data interface

params The submitted data is equivalent to $.ajax data: {}

success Success callback

error Error callback

Here we will talk about JSONP technology

JSONP is a cross-border solution A common way of domain problems

Cross-domain problems: Because the browser has a same-origin policy, cross-domain problems will occur when data is exchanged between different domains

Same origin policy: Data interaction can only occur under the same protocol, same domain name, and same port

Principle of JSONP: You can use the src attribute of the script tag (which will use a callback function to receive data) Not affected by the same origin policy, you can request data from different domains and receive data by setting the callback function

JSONP is Cross-domain method of combining 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.

Does JSONP belong to AJAX? Ajax refers to the technology of asynchronous data interaction by using the xmlhttprequest object. JSONP is obtained by relying on the scriptsrc attribute. It does not belong to ajax.

What are the disadvantages of JSONP? What should I pay attention to when using it?

Cross-domain post processing is not allowed. It should be noted that script tags and callback functions should be dynamically created for each request and destroyed after data acquisition is completed.

If the method is jsonp, you can use jsonp to make cross-domain requests, but be careful to write the value of callback after the url as JSON_CALLBACK

Baidu search small example

The reference here is angular-sanitize.js

var app = angular.module("myapp",[&#39;ngSanitize&#39;])
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:&#39;JSON_CALLBACK&#39;
    }
   }).success(function (results) {
    $scope.dataList = results.s
   })
  }
 })

$location service

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 service

Multiple console output modes

$log.info("info");
$log.warn("warn");
$log.error("error");
$log.log("log");

angularJs service provider configuration

例如

myapp.config(["$interpolateProvider",function($interpolateProvider){
 $interpolateProvider.startSymbol("!!");
 $interpolateProvider.endSymbol("!!");
}])

angular就不认识{{}}了,开始变成!!!!

自定义服务 三种

1.factory

myapp.factory(&#39;serviceName&#39;,function(){
  return ....
})

可以return 字符串、数组、函数、对象(使用最多,最和逻辑)

引入方法和angualr自带的前面加$的服务完全一样,使用方法取决于return出来的是什么东西,自定义服务的服务名还是别加$了

eq:返回一个 两个数之间的随机数的服务

myapp.factory("myService",function(){
 return {
  getRandom:function(a,b){
   return Math.random()*(b-a)+a;
  }
 }
})

自定义的服务可以依赖注入其他服务

myapp.factory(&#39;myHttpService&#39;,[&#39;$http&#39;,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 (&#39;myHttpService&#39;,[&#39;$http&#39;,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:&#39;lily&#39;
    }
  })
  app.controller("firstController",function ($scope,Data) {
    $scope.name="allen";
    $scope.data={
      name:&#39;tom&#39;
    }
    $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就是一个自定义模块

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用axios如何实现ajax请求(详细教程)

在JavaScript中如何实现弹性效果

使用JavaScript如何实现二叉树遍历

在axios中如何实现cookie跨域

The above is the detailed content of How to use it in angularJS?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software