html
<html ng-app="MyServiceApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="framework/bootstrap-3.0.0/css/bootstrap.css">
<script src="framework/angular-1.3.0.14/angular.js"><//script>
<script src="MyService1.js"><//script>
</head>
<body>
<div ng-controller="ServiceController">
<label>用户名</label>
<input type="text" ng-model="username" placeholder="请输入用户名" />
<pre ng-show="username">{{users}}</pre>
</div>
</body>
</html>
js
var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http', function($http) {
var doRequest = function(username, path) {
return $http({
method: 'GET',
url: 'users.json'
});
}
return {
userList: function(username) {
return doRequest(username, 'userList');
}
};
}
]);
myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
function($scope, $timeout, userListService) {
var timeout;
$scope.$watch('username', function(newUserName) {
if (newUserName) {
if (timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(function() {
userListService.userList(newUserName)
.success(function(data, status) {
$scope.users = data;
});
}, 350);
}
});
}
]);
data.json
[{
"name": "《用AngularJS开发下一代WEB应用》"
},{
"name": "《ORCHOME》"
},{
"name": "《ActionScript3.0》"
}]
本例子通过input输入,然后向后台获取数据,进行展示。
userListService
服务$scope.$watch
监控数据模型的变化,监听username。$
开头,会和AngularJS自身的容易混选