开始系统学习一下angular!首先是hello world。根据官网给出的例子,我们一下做出下面这个东西:

<!DOCTYPE html>
<html ng-app>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="angular.js"></script>
<script>
function aaaCtrl($scope) {
$scope.name = "World"
}
</script>
</head>
<body ng-controller="aaaCtrl">
<h1>Hello {{name}}!</h1>
</body>
</html>

这里要注意三个地方:

  • 必须指定ng-app,如果页面上只有一个应用,可以匿名
  • 根据ng-controller划分VM的作用域范围
  • 如果应用是匿名的,那么可以直接在全局作用域下定义控制器。控制器为一个函数,用于生成VM, 要求函数名必须以Ctrl结束,并且它的第一个参数必须叫做$scope,否则报错,因为它是基于静态编译,取其toString()来注入各种服务与处理依赖关系。

但上面这种方式基本不可能用于生产环境,我们看下面的例子:

<!DOCTYPE html>
<html ng-app="test">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="angular.js"></script>
<script>
angular.module("test",[]).controller("aaaCtrl",function($scope){
$scope.name = "World"
})
</script>
</head>
<body ng-controller="aaaCtrl">
<h1>Hello {{name}}!</h1>
</body>
</html>

这时控制器可以随便命名,但第一个参数还是要叫$scope

这是输出结果,其中最重要的是{{}}插值表达式。

{{}}插值表达式相当于knockout的text绑定或avalon的ms-text绑定,当然avalon也可以直接用{{}}插值表达式。它是用于填空文本,当我们要填空HTML时,就要用到另一种绑定了,这在knockout可以用html绑定,avalon可以用{{xxx|html}}或ms-html绑定。在angular, ng-bind-html好像不能用了(看评论,是出BUG了,但至今还没有修复好,此绑定会删提所有内联事件与script标签),但可以用ng-bind-html-unsafe。此外还有一个ng-bind, 它的效果同{{}} 插值表达式。但对于HTML绑定,它都依赖于某一个元素节点,不能做到avalon的{{xxx|html}}的效果。我们可以在这里看实时运行效果,点我

pw:ruby

<!DOCTYPE html>
<html ng-app="test">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="angular.js"></script>
<script>
angular.module("test", []).controller("aaaCtrl", function($scope) {
$scope.xxx = "<strong>dddd</strong>"
})
</script>
</head>
<body ng-controller="aaaCtrl">
1<p>{{xxx}}</p>
2<p ng-bind-html-unsafe="xxx"></p>
3<p ng-bind-html="xxx"></p>
4<p ng-bind="xxx"></p>
<hr/>
</body>
</html>

循环渲染一组数组

<!DOCTYPE html>
<html ng-app="test">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="angular.js"></script>
<script>
//angular会对函数进行静态编译,但那些参数可能被压缩掉,
//因此我们需要在函数前添加相关的服务名,这里不能直接用setTimeout,要用$timeout服务,
//总之angular这样的隐性知识非常多,是目前最难上手的框架,自己制头造了许多概念
angular.module("test", []).controller("aaaCtrl", ["$scope", "$timeout", function($scope, $timeout) {
$scope.friends = [{name: 'John', age: 25}, {name: 'Mary', age: 28}, {name: "Nasami", age: 30}]
$timeout(function() {
$scope.friends.push({name: "add", age: 10})
}, 1000)
}])
//如果不担心被压缩可以这样
//angular.module("test", []).controller("aaaCtrl", function($scope, $timeout) {
// $scope.friends = [{name: 'John', age: 25}, {name: 'Mary', age: 28}, {name: "Nasami", age: 30}]
// $timeout(function() {
// $scope.friends.push({name: "add", age: 10})
// }, 1000)
//}) </script>
</head>
<body ng-controller="aaaCtrl">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</body>
</html>

如果不想用$timeout服务,可以这样写


<!DOCTYPE html>
<html ng-app="test">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="angular.js"></script>
<script>
var a
angular.module("test", []).controller("aaaCtrl", ["$scope", "$timeout", function($scope, $timeout) {
$scope.friends = [{name: 'John', age: 25}, {name: 'Mary', age: 28}, {name: "Nasami", age: 30}]
a = $scope
}])
setTimeout(function() {
a.friends.push({name: "dsfs", age: 44})
a.$digest()//这个不能漏
}, 1000) </script>
</head>
<body ng-controller="aaaCtrl">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</body>
</html>

如果用avalon是这样实现的


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="avalon.js"></script>
<script>
var a = avalon.define("aaa", function(vm) {
vm.friends = [{name: 'John', age: 25}, {name: 'Mary', age: 28}, {name: "Nasami", age: 30}]
})
setTimeout(function() {
a.friends.push({name: "dsfs", age: 44})
}, 1000) </script>
</head>
<body ms-controller="aaa">
I have {{friends.length}} friends. They are:
<ul ms-each-friend="friends">
<li >
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</body>
</html>

事件绑定

<!DOCTYPE html>
<html ng-app="test">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="angular.js"></script>
<script>
angular.module("test", []).controller("SpicyCtrl", function($scope) {
$scope.spice = 'very';
$scope.chiliSpicy = function() {
$scope.spice = 'chili';
}
$scope.jalapenoSpicy = function() {
$scope.spice = 'jalape?o';
}
})
</script>
</head> <body ng-controller="SpicyCtrl">
<button ng-click="chiliSpicy()">Chili</button>
<button ng-click="jalapenoSpicy()">Jalape?o</button>
<p>The food is {{spice}} spicy!</p>
</body>
</html>

avalon的实现与它大同小异


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="avalon.js"></script>
<script>
avalon.define("SpicyCtrl", function($scope) {
$scope.spice = 'very';
$scope.chiliSpicy = function() {
$scope.spice = 'chili';
}
$scope.jalapenoSpicy = function() {
$scope.spice = 'jalape?o';
}
})
</script>
</head> <body ms-controller="SpicyCtrl">
<button ms-click="chiliSpicy">Chili</button>
<button ms-click="jalapenoSpicy">Jalape?o</button>
<p>The food is {{spice}} spicy!</p>
</body>
</html>

创建一个服务

所谓“服务”者,其实类似于jQuery插件这样的东西,但angular需要以“注入”方式来调用的这些功能(说句不好听的,因此害怕压缩让其静态编译失败,才用到这么绕的方式)

我们看如何创建一个应用。有两种方式,都需要调用angular.module实例的一些方法生成。

var myModule = angular.module(‘app’,[]);
//使用实例的factory方法
myModule.factory(‘serviceName’,function() {
var someService;
//工厂方法体,构建someService
return someService; });
angular.module(‘app’,[],function($provide) {
//使用$provide服务的factory方法
$provide.factory(‘serviceId’,function() {
var someService;
//工厂方法体,构建someService
return someService;
});
});

示例:


<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="MainApp">
<head>
<meta charset="UTF-8">
<title>services</title>
</head>
<body>
<div ng-controller="MyController">
<input type="text" ng-model="msg"/>
<button ng-click="saveMsg()">保存信息</button>
<ul>
<li ng-repeat="msg in msgs">{{msg}}</li>
</ul>
</div>
<script src="angular.js" ></script>
<script type="text/javascript">
var app = angular.module("MainApp", [])
app.factory("$notify", ["$window", "$timeout", function(win, timeout) {
var msgs = [];
return function(msg) {
msgs.push(msg);
//只有等到消息条数到达3条时,才一起弹出来
if (msgs.length == 3) {
timeout(function() {
win.alert(msgs.join("\n"));
msgs = [];
}, 10);
}
}
}]) app.controller("MyController",["$scope", "$notify", function($scope, $notify) {
$scope.msgs = [];
$scope.msg = ""
$scope.saveMsg = function() {
$scope.msgs.push($scope.msg);//这里的$scope可改成this
$notify($scope.msg);
$scope.msg = "";
};
}]);
</script>
</body>
</html>

websocket服务

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="MainApp">
<head>
<meta charset="UTF-8">
<title>services</title>
</head>
<body>
<div ng-controller="MyController">
<input type="text" ng-model="msg"/>
<button ng-click="saveMsg()">保存信息</button>
<ul>
<li ng-repeat="msg in msgs">{{msg}}</li>
</ul>
</div>
<script src="angular.js" ></script>
<script src="jquery2.02.js" ></script>
<script type="text/javascript">
var app = angular.module("MainApp", [])
app.factory("$socket", ["$window", "$timeout", function($window, $timeout) {
return function(obj) {
obj.open = obj.open || function() {
console.log("open websocket")
}
obj.close = obj.close || function() {
console.log("close websocket")
}
obj.timeout = obj.timeout || 1000
obj.maxTime = obj.maxTime || 10
var flag = false;
if (flag && $window.WebSocket) {
var wsServer = 'ws://' + document.domain + "/" + obj.url.replace(/^\//, "")
var websocket = new WebSocket(wsServer)
websocket.onopen = obj.open
websocket.onclose = obj.close
websocket.onmessage = function(e) {
obj.success(e.data)
}
websocket.onerror = function(e) {
obj.error(e)
}
}
else {
var success = obj.success
delete obj.success
var error = obj.error
delete obj.error
var errorTime = 0
function callback() {
$.ajax(obj).done(function() {
success.apply(this, arguments)
promise = $timeout(callback, obj.timeout);
}).fail(function(a, b) {
errorTime++
if (errorTime > obj.maxTime) {
arguments[1] = "unconnect"
}
error.apply(this, arguments)
if (errorTime > obj.maxTime || b == "timeout") {
$timeout.cancel(promise)
obj.close()
} else {
promise = $timeout(callback, obj.timeout);
}
})
}
var promise = $timeout(callback, obj.timeout);
obj.open()
}
}
}]) app.controller("MyController", ["$scope", "$socket", function($scope, $socket) {
$scope.msgs = [];
$scope.msg = ""
$scope.saveMsg = function() {
$socket({url: "/resource/region/list", success: function() {
console.log(arguments)
}, error: function() {
console.log(arguments)
}})
};
}]);
</script>
</body>
</html>

更多关于websocket的东西

hello, angular的更多相关文章

  1. Angular杂谈系列1-如何在Angular2中使用jQuery及其插件

    jQuery,让我们对dom的操作更加便捷.由于其易用性和可扩展性,jQuer也迅速风靡全球,各种插件也是目不暇接. 我相信很多人并不能直接远离jQuery去做前端,因为它太好用了,我们以前做的东西大 ...

  2. Angular企业级开发(5)-项目框架搭建

    1.AngularJS Seed项目目录结构 AngularJS官方网站提供了一个angular-phonecat项目,另外一个就是Angular-Seed项目.所以大多数团队会基于Angular-S ...

  3. TypeScript: Angular 2 的秘密武器(译)

    本文整理自Dan Wahlin在ng-conf上的talk.原视频地址: https://www.youtube.com/watch?v=e3djIqAGqZo 开场白 开场白主要分为三部分: 感谢了 ...

  4. angular实现统一的消息服务

    后台API返回的消息怎么显示更优雅,怎么处理才更简洁?看看这个效果怎么样? 自定义指令和服务实现 自定义指令和服务实现消息自动显示在页面的顶部,3秒之后消失 1. 显示消息 这种显示消息的方式是不是有 ...

  5. div实现自适应高度的textarea,实现angular双向绑定

    相信不少同学模拟过腾讯的QQ做一个聊天应用,至少我是其中一个. 过程中我遇到的一个问题就是QQ输入框,自适应高度,最高高度为3row. 如果你也像我一样打算使用textarea,那么很抱歉,你一开始就 ...

  6. Angular企业级开发-AngularJS1.x学习路径

    博客目录 有链接的表明已经完成了,其他的正在建设中. 1.AngularJS简介 2.搭建Angular开发环境 3.Angular MVC实现 4.[Angular项目目录结构] 5.[SPA介绍] ...

  7. Angular企业级开发(4)-ngResource和REST介绍

    一.RESTful介绍 RESTful维基百科 REST(表征性状态传输,Representational State Transfer)是Roy Fielding博士在2000年他的博士论文中提出来 ...

  8. Angular企业级开发(3)-Angular MVC实现

    1.MVC介绍 Model-View-Controller 在20世纪80年代为程序语言Smalltalk发明的一种软件架构.MVC模式的目的是实现一种动态的程序设计,使后续对程序的修改和扩展简化,并 ...

  9. Angular企业级开发(2)-搭建Angular开发环境

    1.集成开发环境 个人或团队开发AngularJS项目时,有很多JavaScript编辑器可以选择.使用优秀的集成开发环境(Integrated Development Environment)能节省 ...

  10. 前端MVC学习总结(一)——MVC概要与angular概要、模板与数据绑定

    一.前端MVC概要 1.1.库与框架的区别 框架是一个软件的半成品,在全局范围内给了大的约束.库是工具,在单点上给我们提供功能.框架是依赖库的.AngularJS是框架而jQuery则是库. 1.2. ...

随机推荐

  1. .net MVC APi调用

    常用的调用方法为Get/Post Get方法: 服务器 public string Get(int id) { return "value"; } 这个直接在网页就可以测试,用 h ...

  2. C#中控件的CheckState和Checked属性区别?

    Checked 和CheckState都是检查控件选中状态,都能判断是否选中控件. 只是Checked 通过布尔判断(true & false): CheckState 通过枚举判断. che ...

  3. poj 2886 Who Gets the Most Candies?(线段树和反素数)

    题目:http://poj.org/problem?id=2886 题意:N个孩子顺时针坐成一个圆圈且从1到N编号,每个孩子手中有一张标有非零整数的卡片. 第K个孩子先出圈,如果他手中卡片上的数字A大 ...

  4. bzoj2878

    又是环套树dp,这次不是我擅长的类型 首先考虑树上的暴力,肯定是穷举起点然后以起点为根dp 我们用g[i]表示以点i为期望走的路径总长,答案就是1/n*Σ(g[i]/d[i]) (d[i]表示点度数) ...

  5. fancybox 无效 失效 直接打开页面, ajax 之后 fancybox对更新的数据无效,Jquery失效 无效

    案例:做个聊天室项目,数据都是通过ajax刷新出来的,而对新数据绑定的fancybox均无效,点击直接打开到了新页面而不是弹窗,解决方法其实很简单   简单分析:ajax加载内容是在$(documen ...

  6. hdu 4612 Warm up(缩点+树上最长链)

    本来就是自己负责图论,结果水了= = 题目其实很裸,就是求桥的数量,只是要新加上一条边罢了.做法:先缩点.再在树上搜最长链(第一场多校的hdu 4607Park Visit就考了最长链,小样,套个马甲 ...

  7. POJ 3469 Dual Core CPU (最小割建模)

    题意 现在有n个任务,两个机器A和B,每个任务要么在A上完成,要么在B上完成,而且知道每个任务在A和B机器上完成所需要的费用.然后再给m行,每行 a,b,w三个数字.表示如果a任务和b任务不在同一个机 ...

  8. ti processor sdk linux am335x evm /bin/setup-uboot-env.sh hacking

    #!/bin/sh # # ti processor sdk linux am335x evm /bin/setup-uboot-env.sh hacking # 说明: # 本文主要对TI的sdk中 ...

  9. 【 D3.js 高级系列 — 7.0 】 标注地点

    有时需要告诉用户地图上的一些目标,如果该目标是只需要一个坐标就能表示的,称其为"标注". 1. 标注是什么 标注,是指地图上只需要一个坐标即可表示的元素.例如,在经纬度(116, ...

  10. 转载RabbitMQ入门(5)--主题

    主题(topic) (使用Java客户端) 在先前的指南中我们改进了我们的日志系统.取代使用fanout类型的交易所,那个仅仅有能力实现哑的广播,我们使用一个direct类型的交易所,获得一个可以有选 ...