<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../angular-1.5.5/angular.min.js"></script> <script> //声明模块 var myapp= angular.module("myApp",[]); //参数一:自定义的模块名 参数二:["mysqlconn"];//借助其它模块的名字 mysqlconn //推断式注入法 $scope作用域对象是控制器和视图之间一个纽带 myapp.controller("democ",["$scope",function(abc){ //依赖注入: 没事你不要来找我,有事我会去找你。 //使用$scope 对象1>创建方法 abc.sayHello=function(){ alert("你好"); } //使用$scope 对象 2>创建属性 }]); </script> </head> <body ng-app="myApp" ng-controller="democ"> <button ng-click="sayHello()">点击</button> </body> </html> 第二<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Titl1</title> <script src="../angular-1.5.5/angular.min.js"> </script> <script> /*AngularJS会假定参数名称就是依赖的名称*/ angular.module("myApp",[]).controller("demoC",function($scope){ //创建控制器时,必须要有$scope--->控制器和视图传递数据 //依赖$scope $scope.sayHello=function (c){ //定义函数的时候, 括号中都是形参 alert("你好"+c); } }); </script> </head> <body ng-app="myApp" ng-controller="demoC"> <button ng-click="sayHello('pig')">点击</button> </body> </html>第三个<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../angular-1.5.5/angular.min.js"></script> <script> angular.module("myApp",[]) .service("gaoyn_greeter",function(){ //使用service创建一个服务 this.sayHello=function(){ alert("你好factory"); } this.saybye=function(){ alert("再见"); } //可以不用return 对象出去,直接使用Service对象--->自动create一个对象出来 }) //使用 angular.module("myApp",[]).controller .controller("democ",["$scope","gaoyn_greeter",function($scope,gaoyn_greeter){ $scope.hi=function(){ gaoyn_greeter.sayHello(); } }]) .controller("demoB",function($scope,gaoyn_greeter){ $scope.hello=function(){ gaoyn_greeter.saybye(); } }); </script> </head> <body ng-app="myApp" ng-controller="democ"> <button ng-click="hi()">问好</button> <button ng-controller="demoB" ng-click="hello()">再见</button> </body> </html>
第四个<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../angular-1.5.5/angular.min.js"></script> <script> angular.module("myApp",[]) .factory("gaoyn_greeter",function(){ var factory={}; // factory.sayHello=function(){ alert("你好factory"); } factory.saybye=function(){ alert("再见factory"); } return factory; }) //使用 angular.module("myApp",[]).controller .controller("democ",["$scope","gaoyn_greeter",function($scope,gaoyn_greeter){ $scope.hi=function(){ greeter.sayHello(); } }]) .controller("demoB",function($scope,gaoyn_greeter){ $scope.hello=function(){ gaoyn_greeter.sayHello(); } }); </script> </head> <body ng-app="myApp" ng-controller="democ"> <button ng-click="hi()">问好</button> <button ng-controller="demoB" ng-click="hello()">hello</button> </body> </html>
依赖注入
最新推荐文章于 2022-03-24 18:51:51 发布