4.angular 服务

news/2025/3/19 6:53:34/

服务是在controller里面引入的服务: 最好是内部服务在前面,自定义服务在后面

内部服务

$scope

  • $scope.$watch(‘属性名’, function(newVal, oldVal) {}, true) true是深度监听,对象函数等
  • $scope.$apply 触发页面更新,里面传入回调函数,比如说之前那个settimeout这种更改数据页面没变化,可以会用这个,我觉得跟 vue中的 s e t 似的 . set似的. set似的.scope.$apply(function() { $scope.* = ‘hi’})

$timeout, $interval

$filter

$rootScope 根服务

$http

  • method
  • url
  • success
  • error
  • 简写直接就是$http.get().success() 我项目中写的是.then
  • 百度下拉搜索例子(这种教程上写法报错,但是基本看下怎么写的得了)
javascript"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><input type="text" ng-model="name" ng-keyup="change(name)"><!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script> --><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.controller('Aaa', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {var timer = null$scope.change = function(name) {$timeout.cancel(timer)timer = $timeout(function() {$http({method: 'JSONP',url: 'http:www.list'// url: 'https://www.baidu.com/s?ie=utf-8&newi=1&mod=1&isbd=1&isid=f4ef53c100060ac3&wd='+name+'&rsv_spt=1&rsv_iqid=0x93e5cb7c0001e73c&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_dl=tb&rsv_enter=0&oq=a&rsv_btype=t&rsv_t=ebbcgxsrZUUmgNSW8%2Fr4PljCkX5%2FL8NvNDz5M3ed1hm27nDOB9PHaRTlQ7nkmZ0N5Nbb&rsv_pq=f4ef53c100060ac3&bs=a&rsv_sid=37377_36552_36461_37361_36885_34813_36804_37260_26350_22159_37223&_ss=1&clist=8e7d48f30f6acc95&hsug=&f4s=1&csor=1&_cr1=34739',}).success(function(data) {console.log(data)})}, 1000)}}])</script>
</body>
</html>

$location

  • absUrl() // 绝对编码地址
  • path() // 跟路由挂钩
  • replace()
  • hash()
  • search()
  • url()
  • host()
  • port()
  • protocol()
javascript"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.controller('Aaa', ['$scope', '$location', function($scope, $location) {console.log($location.absUrl()) // file:///C:/Users/17903/Desktop/moni/index.html#!/绝对路径$location.path('/aaa/bbb/ccc').replace() // file:///C:/Users/17903/Desktop/moni/index.html#!/aaa/bbb/ccc 路由, replace()是没有历史记录console.log($location.path()) // /aaa/bbb/ccc$location.hash('hello') // file:///C:/Users/17903/Desktop/moni/index.html#!/aaa/bbb/ccc#helloconsole.log($location.hash()) // hello$location.search({ name: 'zhaohui'}) // file:///C:/Users/17903/Desktop/moni/index.html#!/aaa/bbb/ccc?name=zhaohui#helloconsole.log($location.url()) // /aaa/bbb/ccc?name=zhaohui#helloconsole.log($location.host()) // ipconsole.log($location.port()) // 端口号console.log($location.protocol()) // 协议}])</script>
</body>
</html>

$anchorScroll -锚点跳转

javascript"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.box {width: 300px;height: 600px;border: 1px solid #000;}ul {position: fixed;right: 200px;top: 30px;}</style>
</head>
<body ng-app="myApp" ng-controller="Aaa"><ul><li ng-repeat="id in ['1', '2', '3', '4', '5']" ng-click="change('div'+ id)">{{id}}aaaa</li></ul><div class="box" ng-repeat="id in ['1', '2', '3', '4', '5']" ng-attr-id="div{{id}}">{{id}}</div><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.controller('Aaa', ['$scope', '$location', '$anchorScroll', function($scope, $location, $anchorScroll) {$scope.change = function(id) {$location.hash(id)$anchorScroll() // 引入这个$anchorScroll就行,自动hash跳转id,但是因为这个如果一样的不跳转,所以在这里又调用了下}}])</script>
</body>
</html>

$cacheFactory 存储

  • info()
  • put()
  • get()
  • remove()
  • 配置capacity
javascript"><!DOCTYPE html>
<html lang="en"> 
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.controller('Aaa', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {var cache = $cacheFactory('myCache', { capacity: 2 }) // capacity限制只能存储两条cache.put('name', 'hello') // 设置console.log(cache.info()) // {capacity: 2, id: 'myCache', size: 1}console.log(cache.get('name')) // hello获取cache.remove('name') // 删除console.log(cache.get('name')) // undefined}])</script>
</body>
</html>

$log – 其实跟console.log差不多

  • log // $log.log(‘hello’)
  • info()
  • warn()
  • error()
  • debug()

$interpolate

-插值计算(比如说输入框中输入{{name}}, 就找$scope.name显示替换),
在这里插入图片描述

javascript"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><!-- <span>{{ name }}</span> --><textarea ng-model="body"></textarea><span>{{ showText }}</span><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.controller('Aaa', ['$scope', '$interpolate', function($scope, $interpolate) {$scope.name = 'zhaohui'$scope.$watch('body', function(newBody) {if (newBody) {var tem = $interpolate(newBody)$scope.showText = tem({ name: $scope.name })}})}])</script>
</body>
</html>

$q

  • promise实现
  • defer()
  • resolve()
  • reject()
  • notify() // 消息通知
  • then() --成功失败之后的回调
javascript"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.controller('Aaa', ['$scope', '$q', function($scope, $q) {var dfd = $q.defer()function show() {setTimeout(function() {dfd.resolve()}, 2000)return dfd.promise}show().then(function() {alert('成功')}, function() {alert('shibai')})}])</script>
</body>
</html>

项目中使用–attachfileupload

javascript"><!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body ng-app="myApp" ng-controller="Aaa"><script src="./js/angular.js"></script><script>var m1 = angular.module("myApp", []);m1.controller("Aaa", ["$scope","$q",function ($scope, $q) {function upload() {var defer = $q.defer();var promise = defer.promise;promise.success = function (fn) {promise.then(function (response) {fn(response);});return promise;};promise.error = function (fn) {promise.then(null, function (response) {fn(response);});return promise;};promise.progress = function (fn) {promise.then(null, null, function (response) {fn(response);});return promise;};return promise;}function fnUploadFiles() {var def = $q.defer();upload().success(function (data) {def.resolve(data);}).error(function (data) {def.reject(data);}).progress(function (data) {def.notify(data);});return def.promise;}fnUploadFiles().then(function (data) {console.log("chenggongn", data);},function (data) {console.log("shibai", data);},function (data) {console.log("progress", data);});},]);</script></body>
</html>可以链式调用
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body ng-app="myApp" ng-controller="Aaa"><script src="./js/angular.js"></script><script>var m1 = angular.module("myApp", []);m1.controller("Aaa", ["$scope","$q",function ($scope, $q) {function upload() {var defer = $q.defer();var promise = defer.promise;promise.success = function (data) {console.log(data);return promise;};promise.error = function (data) {console.log(data);return promise;};promise.lala = function (data) {console.log(data);return promise;};return promise;}function fnUploadFiles() {var def = $q.defer();upload().success("success").error("error").lala("nihao");return def.promise;}fnUploadFiles();},]);</script></body>
</html>

angularjs的供应商

  • 服务的相关初始化配置操作(很多服务都可以,直接在后面加Provider)
  • config
  • $interpolate --插值
    • startSymbol()
    • endSysbol()
  • $anchorScroll
    • disableAutoScrolling() —配置不可以自动跳转了,直接需要重新触发$anchorScroll()手动跳转
      插值改变
      在这里插入图片描述
javascript"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><!-- <span>{{ name }}</span> --><textarea ng-model="body"></textarea><span>@@ showText @@</span><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.config(['$interpolateProvider', function($interpolateProvider) {$interpolateProvider.startSymbol('@@')$interpolateProvider.endSymbol('@@')}])m1.controller('Aaa', ['$scope', '$interpolate', function($scope, $interpolate) {$scope.name = 'zhaohui'$scope.$watch('body', function(newBody) {if (newBody) {var tem = $interpolate(newBody)$scope.showText = tem({ name: $scope.name })}})}])</script>
</body>
</html>

自定义服务

  • factory() // 第一个参数名字,第二个可以是函数或者跟controller似的[]
  • provider() --也是服务,但是比factory好在可以config初始化配置(使用angularjs的供应商), $get
javascript"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><textarea ng-model="body"></textarea><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.factory('myFactory', function() {return {name: 'hello',show: function() {return this.name}}})m1.provider('myProvider', function() {return {age: '18',$get: function() {return {name: 'zhaohui',age: this.age,show: function() {return this.name + this.age}}}}})m1.config(['myProviderProvider', function(myProviderProvider) {console.log('myProviderProvider', myProviderProvider)myProviderProvider.age = '20'}])m1.controller('Aaa', ['$scope', 'myFactory', 'myProvider', function($scope, myFactory, myProvider) { // 一般自定義放在定義好的服務後面console.log(myFactory.show()) // helloconsole.log(myProvider.show()) // zhaohui18, 中間配置了就是zhaohui20}])</script>
</body>
</html>

上面优化
可以多个模块使用
service.js

javascript">var m1 = angular.module('myModule1', [])
m1.provider('myProvider', function() {return {age: '18',$get: function() {return {name: 'zhaohui',age: this.age,show: function() {return this.name + this.age}}}}
})

index.html

javascript"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><textarea ng-model="body"></textarea><script src="./public/angular.js"></script><script src="./service.js"></script><script>var m2 = angular.module('myApp', ['myModule1'])m2.config(['myProviderProvider', function(myProviderProvider) {console.log('myProviderProvider', myProviderProvider)myProviderProvider.age = '20'}])m2.controller('Aaa', ['$scope', 'myProvider', function($scope, myProvider) { // 一般自定義放在定義好的服務後面console.log(myProvider.show()) // zhaohui18, 中間配置了就是zhaohui20}])</script>
</body>
</html>
  • service() -构造函数方式写法,面向对象写法
  • constant() --定义常量,可以用。config,但是這個裏面不用後面加Provider.下面這倆不用基本
  • value() – 也是定义常量,但是跟constant区别就上面那个可以config配置
javascript"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body ng-app="myApp" ng-controller="Aaa"><textarea ng-model="body"></textarea><script src="./public/angular.js"></script><script>var m1 = angular.module('myApp', [])m1.service('myService', Fn)function Fn() {this.name = 'hello'}m1.constant('myConstant', 'LALALLA')m1.config(['myConstant', function(myConstant) {console.log('myConstant', myConstant) // LALALLA}])m1.controller('Aaa', ['$scope', 'myService', 'myConstant', function($scope, myService, myConstant) {console.log(myService.name) // helloconsole.log(myConstant) // LALALLA}])</script>
</body>
</html>

项目中

  • 看项目中基本是使用的.service,,比如弹框等基本都是返回return{ 名称: 定义的函数 }然后其他地方就可以直接abcWidth.fn()
  • 其次可能用factory,也可以返回对象函数拉乱七八糟的,使用也都差不多跟.service
  • provider 这个我看用的基本在插件中

http://www.ppmy.cn/news/1580259.html

相关文章

[Banana Pi BPI-R4] RDK 和联发科推出Wi-Fi 7 宽带 CPE 的新硬件参考平台

全新参考板可帮助运营商、CPE 制造商和应用程序开发商轻松快速地测试和推出下一代 RDK-B 路由器、网关和应用程序联发科与 RDK 合作基于 Banana Pi 开源硬件项目打造全新宽带参考板 巴黎&#xff0c;2024 年 10 月 3 日——在NetworkX年度会议召开之前**&#xff0c;** RDK 管…

网络爬虫【简介】

我叫补三补四&#xff0c;很高兴见到大家&#xff0c;欢迎一起学习交流和进步 今天来讲一讲爬虫 一、网络爬虫的定义 网络爬虫&#xff08;Web Crawler&#xff09;&#xff0c;又称为网络蜘蛛、网络机器人等&#xff0c;是一种按照一定规则自动抓取互联网信息的程序或脚本。它…

IP风险度自检,互联网的安全“指南针”

IP地址就像我们的网络“身份证”&#xff0c;而IP风险度则是衡量这个“身份证”安全性的重要指标。它关乎着我们的隐私保护、账号安全以及网络体验&#xff0c;今天就让我们一起深入了解一下IP风险度。 什么是IP风险度 IP风险度是指一个IP地址可能暴露用户真实身份或被网络平台…

基于Python+Ollama DeepSeek与MySQL进行数据分析探索

目录 1、前言 2、环境准备 3、本地部署 3.1、安装ollama 3.2、部署deepseek-r1模型 4、Python接入本地模型 4.1、示例代码 4.2、附加一些功能 4.3、其他的数据库 4.3.1、PostgreSQL 示例 4.3.2、SQLite 示例 5、总结 1、前言 在当今数据驱动的时代&#xff0c;数据…

qt介绍自定义插件 三

代码结构 主要编写这两个文件 #ifndef TBATTERY_H #define TBATTERY_H#include <QWidget> #include <QtUiPlugin/QDesignerExportWidget> class QDESIGNER_WIDGET_EXPORT TBattery : public QWidget {Q_OBJECT private:QColor colorBackgroundQt::white;QColor c…

2025 centos系统安装docker并迁移docker,docker安装到指定的目录以及文件迁移,docker迁移文件

需求&#xff1a;centos7系统&#xff0c;由于硬盘有限&#xff0c;需要把docker安装到指定的目录下&#xff0c;怎么安装&#xff1f; 1. 安装Docker引擎 步骤1.1&#xff1a;卸载旧版本&#xff08;如有&#xff09; sudo yum remove -y docker \docker-client \docker-cl…

产业数字化转型业务蓝图规划(63页PPT)(文末有下载方式)

产业数字化转型业务蓝图规划&#xff08;63页PPT&#xff09;详细解读 详细资料请看本解读文章的最后内容。 在当今数字化浪潮的推动下&#xff0c;物流产业的数字化转型已成为行业发展的必然趋势。本文将对《产业数字化转型业务蓝图规划》进行详细解读&#xff0c;深入剖析物…

蓝桥杯动态规划实战:从数字三角形到砝码称重

适合人群&#xff1a;蓝桥杯备考生 | 算法竞赛入门者 | DP学习实践者 目录 一、我的动态规划入门之路 1. 数字三角形&#xff1a;经典DP首战告捷 2. 砝码称重&#xff1a;背包问题的变形 二、蓝桥杯高频算法考点 三、蓝桥杯DP专项训练题 四、备考建议 一、我的动态规划入…