factory

作者: 晨雪落客 | 来源:发表于2019-03-25 17:02 被阅读0次

<!DOCTYPE html>

<html lang="en" ng-app="myApp">

<head>

<meta  charset="UTF-8">

<title>title>Node app</title>

<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>

<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular-route.min.js"></script>

</head>

<body >

<header>

<p>Node app</p>

</header>

</body>

<div ng-controller="HomeController">

<h3>Button hits: {{ hits }}</h3>

<button ng-click="registerHit()">HIT ME, if you dare</button>

</div>

<script type="text/javascript">

angular.module('myApp.services',[])

.factory('HitService',function($q,$http){

var service  = {

count:function(){

var d=$q.defer();

$http.get('/hits')

.success(function(data, status) {

d.resolve(data.hits);

}).error(function(data, status) {

d.reject(data);

});

return d.promise;

},

registerHit:function(){

var d=$q.defer();

$http.post('/hits',{})

.success(function(data,status){

d.resolve(data.hits);

}).error(function(data,status){

d.reject(data);

});

//Promise就是一种对执行结果不确定的一种预先定义

                        return d.promise;

}

}

return service;

});

angular.module('myApp',['ngRoute','myApp.services'])

.controller('HomeController',function($scope,HitService){

HitService.count().then(function(data){

$scope.hits = data;

});

HitService.registerHit().then(function(data){

$scope.hits = data;

});

})

</script>

</html>

相关文章

网友评论

      本文标题:factory

      本文链接:https://www.haomeiwen.com/subject/guebvqtx.html