您的位置:首页 > Web前端

我也谈“the difference between Factory, Service, and Provider in Angular”

2015-04-23 15:35 666 查看
看完这篇文章之后的理解与实践:原文地址:http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/

<!doctype html>
<html ng-app="myModule">
<head>
<script src="../lib/js/angular.min.js"></script>
</head>
<body>
<script>
var myModule = angular.module('myModule', []);
myModule.factory('greeter', function($window){
return {
greet: function(text){
$window.alert(text);
}
};
});

function myController($scope,greeter,notify){
$scope.sayHello = function(){
greeter.greet('Hello, world!');
}
$scope.callNotify = function(msg){
notify.say(msg);
};
//        scope.callNotify = function(msg){
//            notify(msg);
//        };
}

//    myModule.factory('notify', function($window){
//       var msgs = [];
//        return function(msg){
//            msgs.push(msg);
//            if(msgs.length==3){
//                console.info(msgs);
//                $window.alert(msgs.join("\n"));
//                msgs = [];
//            }
//        }
//    });
myModule.service('notify', function($window){
var msgs = [];
return this.say = function(msg){
msgs.push(msg);
if(msgs.length==3){
console.info(msgs);
$window.alert(msgs.join("\n"));
msgs = [];
}
}
});
</script>
<div ng-controller="myController">
<button ng-click="sayHello()">Hello</button>
<input type="text" ng-model="message" />
<button ng-click ="callNotify({{'message'}})">Notify</button>
</div>
</body>
</html>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: