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