好好爱自己!

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

看完这篇文章之后的理解与实践:原文地址: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>

  

posted @ 2015-04-23 15:35  立志做一个好的程序员  阅读(302)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处