angularJS1笔记-(7)-控制器的合理使用(显示和隐式的依赖注入)


AngularJS依赖注入
1.隐式注入:不需要开发人员干预,angularJS自动根据参数的名称识别和注入数据
app.controller("myCtrl".function($scope) {
$scope.name="xiaoming"
})
隐式注入如果一但要进行优化,就会存在问题
2.显式注入:开发人员通过字符串描述,告诉angular需要注入的对象名称,这样JS
在进行优化的过程中,对字符串是不会压缩的,显式的进行依赖描述
app.controller("myCtrl",["$scope",function(s){
s==$ssope
}])
项目实际开发过程中使用显式注入方式!

html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<div ng-app="myApp">
    <div ng-controller="secondController">

    </div>
    <div ng-controller="otherController">

    </div>
</div>

<script type="text/javascript" src="../../vendor/angular/angularJs.js"></script>
<script type="text/javascript" src="app/index.js"></script>

<script>
</script>

</body>
</html>

  js:

var myApp = angular.module('myApp', [], function () {

})
    //隐式的依赖注入
    // .factory('CustomeService', function ($window) {
    //     console.log($window);
    // })
    //显示的依赖注入
    .factory('CustomService',['$window',function (a) {//a参数就是$window
        console.log(a);
    }])
    //隐式的依赖注入
    .controller('secondController', function ($scope, CustomService) {

    })
// //显式的依赖注入(推荐使用)
// .controller('secondController', ['$scope', '$filter', function (a, b) {
//     console.log(b('json')([1, 2, 3, 4, 5]));
// }])


function otherController(a) {
    console.log(a);
}
otherController.$inject = ['$scope']; //此处的$scope就是上面的参数a

  



转载于:https://www.cnblogs.com/yk123/p/6830223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值