AngularJS依賴注入

來源:互聯網
上載者:User

標籤:mod   rip   變數   com   function   隱式   type   方便   mon   

AngularJS的依賴注入有兩種,一種是顯式依賴注入,一種是隱式依賴注入,推薦用顯式依賴注入,js壓縮後不會因為參數問題而報錯

demo6.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div ng-app="myApp">    <div ng-controller="myController">        {{data}}    </div>    <div ng-controller="otherController">        {{otherData}}    </div></div><script type="text/javascript" src="../common/angular/angularjs.js"></script><script type="text/javascript" src="demo6.js"></script></body></html>

demo6.js

/** * Created by Administrator on 2017/7/23. */var myApp = angular.module(‘myApp‘, [], function () {    })    //顯式依賴注入 myFactory 工廠    .factory(‘myFactory‘, [‘$window‘, function (a) {        console.log("window:" + a);        return "myFactory";    }])    /**     * 1.隱式依賴注入,直接寫 function ($scope) 而且參數名稱必須是$scope,$scope這個單詞不能改     */    .controller(‘myController‘, function ($scope) {        $scope.data = ‘張三‘;    })    /**     * 2.顯式依賴注入 第二個參數用數組 [] 的方式表示,$scope 就是後面functioin的參數a,$filter 就是參數b,多個參數以此類推     * 推薦使用顯示依賴注入,一般function(a,b,c)裡面的參數名,最好與數組[]前面的變數名一致,方便閱讀     */    .controller(‘myController‘, [‘$scope‘, ‘$filter‘, ‘myFactory‘, function (a, b, c) {        a.data = ‘張三‘;        console.log(a);        console.log(b(‘json‘)([1, 2, 3]));        console.log(c);    }])/** * 定義了一個全域的函數 otherController ,可以通過otherController.$inject 的方式 顯式依賴注入 $scope , * 這裡的 a 就是指 $scope * @param a */function otherController(a) {    a.otherData = ‘李四‘;}otherController.$inject = [‘$scope‘];

 

AngularJS依賴注入

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.