1.内联式注入(最基本的方式)
<!DOCTYPE html> <html ng-app="MyModule"> <head> <title>最基本的依赖注入方式</title> <Meta charset="utf-8"/> <script src="../Script/angular.min.js" type="text/javascript"></script> <script src="base.js"></script> <link rel="stylesheet" href="../bootstrap-3.0.0/css/bootstrap.css"> </head> <body> <div> <div ng-controller="MyCtrl" style="text-align: c"> <span style="font-size: 20px;">{{gameName}}</span> </div> </div> </body> </html>
//最基本的依赖注入方式 var MyModule = angular.module("MyModule",[]); MyModule.controller('MyCtrl',['$scope',function($scope){ //可以修改参数,如$scope1,但下面必须同时改 $scope.gameName = "海哥帅!" } ]);
2.推断型注入
//推断型注入方式:函数参数的名称必须要和被注入的对象相同 var MyModule = angular.module("MyModule",[]); var MyCtrl = function($scope){ $scope.gameName = "海哥帅!"; } MyModule.controller('MyCtrl',MyCtrl);
3.声明式注入
//声明式注入 var MyModule = angular.module("MyModule",[]); var MyCtrl = function(thisISMyName){ //参数名称可以随意变化 thisISMyName.gameName = "海哥帅!"; } MyCtrl.$inject = ['$scope']; //加载模块 MyModule.controller('MyCtrl',MyCtrl);原文链接:https://www.f2er.com/angularjs/146642.html