1 使用Module(模块)组织依赖关系
<!DOCTYPE html> <html ng-app="shoppingModule"> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> <script> var shoppingModule = angular.module("shoppingModule", []); shoppingModule.factory("Items", function () { var items = {}; items.query = function () {
//在服务器中拉取数据 return [ { name: 'Jackey', age: 25 }, { name: 'Cassi', age: 20 }, { name: 'JC', age: 1.2 } ]; }; return items; }); shoppingModule.controller("shoppingController", function ($scope, Items) { $scope.Items = Items.query(); }); </script> </head> <body> <div ng-controller="shoppingController"> <ul> <li ng-repeat="item in Items"> {{item.name}} </li> </ul> </div> </body> </html>
需要注意的点是
1 controller里面
$scope.Items = Items.query();
2 factory里面的items.query = function(){};
2 添加过滤器
<!DOCTYPE html> <html ng-app="shoppingModule"> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> <script> var shoppingModule = angular.module("shoppingModule", []); shoppingModule.factory("Items", function () { var items = {}; items.query = function () { return [ { name: 'Jackey', age: 25 }, { name: 'Cassi', age: 20 }, { name: 'uuuuujC', age: 1.2 } ]; }; return items; }); //过滤器 shoppingModule.filter("titleCase", function () { var titleCase = function (input) { return input.charAt(0).toUpperCase() + input.slice(1); }; return titleCase; }); shoppingModule.controller("shoppingController", function ($scope, Items) { $scope.Items = Items.query(); }); </script> </head> <body> <div ng-controller="shoppingController"> <ul> <li ng-repeat="item in Items"> {{item.name | titleCase}} </li> </ul> </div> </body> </html>