文章出處

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="MainApp">
<head>
    <meta charset="UTF-8">
    <title>explicit-inject-service</title>
</head>
<body>
<div ng-controller="MyController">
    <input type="text" ng-model="msg"/>
    <button ng-click="saveMsg()">save msg</button>
    <ul>
        <li ng-repeat="msg in msgs">{{msg}}</li>
    </ul>
</div>>
<script src="js/angular.js" type="text/javascript"></script>
<script type="text/javascript">
    var app = angular.module("MainApp",[],function($provide) {
        $provide.factory("notify",["$window","$timeout",function(win,timeout) {
            //這里是服務依賴服務,通過這種顯式的方式,參數名可以亂填,但順序要對應
            var msgs = [];
            return function(msg) {
                msgs.push(msg);
                if(msgs.length==3) {
                    timeout(function() {
                        win.alert(msgs.join("\n"));
                        msgs = [];
                    },10);
                }
            }
        }]);
    });

    function MyController($s,$noti) {
        //這里是controller依賴服務,通過這種顯式的方式,參數名可以亂填,但順序要對應
        $s.msgs = [];
        $s.saveMsg  = function() {
            this.msgs.push(this.msg);
            $noti(this.msg);
            this.msg = "";
        };
    }
	
	//這個就是讓controller里面的$s指向$scope,$noti指向notify這個服務
    MyController.$inject = ['$scope','notify'];
  //有顯示依賴和隱示依賴
</script>
</body>
</html>

  


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()