您的位置:首页 > Web前端 > AngularJS

[Ng]Angular应用点概览 ( 持续更新 )

2015-11-25 23:06 741 查看
1. 使用模块化写法。

var app = angular.module('myApp', []);
app.controller('TextController', function($scope) {
$scope.txt = {'title':'some txt'};
});


  [] 表示此模块不依赖其它模块。

  ng-model, ng-repeat, ng-change,ng-click(相当于onclick),ng-dblclick(相当于ondblclick)

  ng-repeat可以通过$index返回当前引用的元素序号;
  还可以通过$first、$middle及$last,ng-repeat指令返回布尔值,告诉你当前元素是否是集合中的第一个元素、中间的某个元素,或者最后一个元素。

  注意:避免angular顾虑掉重复索引的数据,加 track by $index。(解决使用ng-repeat时报错 “ Error:ngRepeat:dupes ”)
  track by 应在 filter (如:orderBy) 之后使用。

<table ng-controller="getList">
<tr ng-repeat="item in list">
<td ng-repeat="k in item track by $index">
{{k}}
</td>
</tr>
</table>


  

<!--遍历对象, 可以取到键-->
<li ng-repeat="(key, value) in obj">{{key}} | {{value}}</li>


  

  ng-repeat 高级用法:http://www.cnblogs.com/cook/p/4582860.html

  ng-options参考:https://docs.angularjs.org/api/ng/directive/select

  ng-options分组:http://www.cnblogs.com/xing901022/p/5122702.html

2. 首页使用ng-bind代替{{}},避免解析前用户看到花括号。

<p>{{data.member}}</p>
<p ng-bind="data.member"></p>


对于index.html中的数据绑定操作,建议使用ng-bind。

3. $wath() 监视表达式,监控数据模型的变化。

function($scope) {
$scope.funding = {startingEstimate: 0};
computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
}
$scope.$watch('funding.startingEstimate', computeNeeded);
}


  当$watch第一参数中的表达式值发生改变,则执行第二个参数中的函数,第三个参数为true则遍历第一个参数中表达式的属性,当任何一个属性发生变化时就调用函数。

4. ng-submit="requestFunding()", ng-submit自动阻止浏览器执行默认的POST操作,当表单提交时执行指定函数。
  注意:此时form不能有action属性,不然也一样会提交。

  使用表单编辑时,需要选中radio这种input时,使用ng-checked,true时选中。如:ng-checked="list.use_scope==key"

5. 非侵入式JavaScript

<div ng-click="doSomething();">


  不在全局命名空间中进行操作,指定的表达式只能访问元素控制器作用域范围内的函数和数据。

6. 迭代型元素

$scope.insertTom = function() {
$scope.students.splice(1, 0, {name:'Tom Thumb', id: '4'});
}


7. 隐藏和显示: ng-show, ng-hide

$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
}


8. css类和样式:ng-class, ng-style

.error {background-color: red;}

<div ng-controller='headerController'>
<div ng-class='{error: isError, warning: isWarning}'>{{messageText}}</div>
<button ng-click='showError();'>错误提示</button>
<tr ng-repeat='restaurant in directory' ng-click='selectRestaurant($index)' ng-class='{selected: $index==selectedRow}'>
<td>{{restaurant.name}}</td>
</tr>
</div>

function HeaderController($scope) {
$scope.isError = false;
$scope.isWarning = false;
$scope.showError = function() {
$scope.messageText = '这是错误信息';
$scope.isError = true;
$scope.isWarning = false;
}
}
function RestaurantTableController($scope) {
$scope.directory = [{
name: 'The handsome heifer', cuisine: 'BBQ',
name: 'Greens green greens', cuisine: 'salads'
}];
$scope.selectRestaurant = function(row) {
$scope.selectedRow = row;
}
}
# 使用ng-class,json键为css类名,值为true则应用此类。


  在img和a标签上进行数据绑定时,使用{{ }}无法生效,使用ng-src 和 ng-href 才能拦截到数据绑定请求。

9. 使用模块(module)组织依赖关系

<html ng-app='ShoppingModule'>
<body ng-controller='ShoppingController'>
<table><tr>
<td>{{item.title}}</td>
</tr></table>
</body>
// 创建模型
var shoppingModule = angular.module('ShoppingModule', []);
// Factory服务工厂,创建itemFactory接口,访问服务端
ShoppingModule.factory('itemFactory', function() {
var items = {};
items.query = function() {
// 真实数据从服务端拉取
return [
{title: '', description: ''}
];
};
return items;
});

// Service
ShoppingModule.service('itemService', function() {
  this.title = 'def';
})

// Provider
ShoppingModule.provider('itemProvider', function() {
  this.$get = function() {
    return {title: 'ghi'};
  }
});

// 使用, 注意依赖自定义的service不需要加引号
ShoppingModule.controller('shoppingController', function($scope, itemFactory, itemService, itemProvider) {
  $scope.res = itemFactory.query();
  $scope.res2 = itemService;
  $scope.res3 = itemProvider;
});


  服务自身可以互相依赖,在大多数应用中,创建供所有代码使用的单个模块,并把所有依赖的东西都放入这个模块中,就能工作得很好。
  
  如果引入了SnazzyUIWidgets和SuperDataSync模块,那么应用的模块声明会像这样:
  var appMod = angular.module(’app’, [’SnazzyUIWidgets’, ’SuperDataSync']);

  更多例子:http://ju.outofmemory.cn/entry/121904
       https://segmentfault.com/q/1010000002540348

10. 过滤器

{{ 表达式 | 过滤器名称 : 参数1 : 参数2 }}
{{ 12.9 | currency | number:0 }} // $13

// 自己编写首字母大写过滤器:
var homeModule = angular.module('HomeModule', []);
homeModule.filter('titleCase' function() {
var titleCaseFilter = function(input) {
var words = input.split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + Words[i].slice(1);
}
return words.join(' ');
};
return titleCaseFilter;
});
<body ng-app='HomeModule', ng-controller='HomeController'>
<h1>{{ pageHeading | titleCase }}</h1>
</body>
function HomeController($scope) {
$scope.pageHeading = 'page title';
}


11. 用路由和$location切换视图

# index.html
<html ng-app='AMail'>
<body>
<h1>A-Mail</h1>
<div ng-view></div>
</body>
</html>

# list.html
<table><tr ng-repeat='message in messages'>
<td>{{ message.sender }}</td>
<td><a href='#/view/{{ message.id }}'>{{ message.subject }}</td>
<td>{{ message.date }}</td>
</tr></table>

# detail.html
<div>
<strong>To:</strong>
<span ng-repeat='recipient in message.recipients'>{{ recipient }}</span>
</div>
<a href='#/'>返回列表</a>


# controller.js

// 为AMail服务创建模块
var aMailServices = angular.module('AMail', []);

// 在url、模板和控制器之间建立映射关系
function emailRouteConfig($routeProvider) {
$routeProvider.
when('/', {controller: ListController, templateUrl: 'list.html'}).
// 在id前面加一个冒号,指定一个参数化的url
when('/view/:id', {controller: DetailController, templateUrl: 'detail.html'}).
otherwise({redirectTo: '/'});
}

// 配置路由
a.MailServices.config(emailRouteConfig);

// 虚拟数据
messages = [{}];

// 给邮件列表数据的控制器
function ListController($scope) {
$scope.messages = messages;
}

// 从路由信息(url中解析的)中获取邮件id,然后用它找到正确的邮件对象
function DetailController($scope) {
$scope.message = messages[$routeParams.id];
}


  angular-ui-router例子:

  http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref

  http://www.cnblogs.com/koleyang/p/4522543.html

12. 与服务器交互

// 查询代码, 模板中使用items,与服务端交互最好写在服务里
function ShoppingController($scope, $http) {
$http.get('/products').success(function(data, status, headers, config) {
$scope.items = data;
});
}


13. 编写指令

var appModule = angular.module('app', []);
appModule.directive('ngbkFocus', function() {
return {
link: function(scope, element, attrs, controller) {
element[0].focus();
}
};
});
// 使用
<button ngbk-focus>被聚焦的按钮</button>
var appModule = angular.module('app', ['directives']);


 以Angular的方式切换bootstrap Tab的指令:https://www.grobmeier.de/bootstrap-tabs-with-angular-js-25112012.html

14. 表单校验

<form name='addUserForm' ng-controller='AddUserController'>
<input ng-module='user.first' required>
<input type='email' ng-module='user.email' required>
<input type='number' ng-module='user.email' required>
<button ng-disabled='!addUserForm.$valid'>提交</button>
</form>


  required属性和email、number类型由angular适配支持非html5浏览器;
$valid属性获取表单的校验状态,输入项都合法时,angular将属性设为true.

function AddUserController($scope) {
$scope.message = '';
$scope.addUser = function() {
// 保存到数据库中
}
}


From:《用angularjs开发下一代web应用》& Internet.

其余推荐:Angular.js 介绍及实践教程

架构感知:



Link: /article/5289438.html

@黑眼诗人 <www.farwish.com>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: