声明一个controller有很多种写法都能运行成功, 那么各种方法的的却别是什么呢,下面咱们讲讲。
###推断式注入
var testModule = angular.module('testModule', []);
testModule.controller('testCtrl', function($scope){
// xxx
});
推断性注入是angular根据你传入的参数(这里只有$scope)来给你自动注入。
但是这样有个坏处, 就是如果你的代码发布的时候被压缩, $scope可能被压缩成a, 这样代码就会报错了。。
所以这种方式不被推荐
###声明式注入
var testModule = angular.module('testModule', []);
var testCtrl = function($scope, rs){
// 这里的rs其实就是$rootScope
}
testCtrl.$inject = ['$scope', '$rootScope'];
testModule.controller('testCtrl', testCtrl);
就要多写一行, 别的没啥影响, 觉得这样挺好的, 还有就是随便压缩代码。
###内联式注入
var testModule = angular.module('testModule', []);
testModule.controller('testCtrl', ['$scope', '$rootScope', function(scope, rs){
// scope就是$scope, rs 就是rootScope
// 当然依然可以起名叫$scope
}]);
一样可以随便压缩代码
var testModule = angular.module('testModule', []);
testModule.factory('book', function () {
return {
name: '程序员宝典'
}
});
testModule.controller('testCtrl', ['$scope', '$injector',
function($scope, $injector){
$injector.invoke(function(book){
// 这样一样可以引入book这个factory
console.log(book.name);
})
}
]);
看看angular官方给的例子吧
https://docs.angularjs.org/api/ng/function/angular.injector
今天才了解了这些玩意是个什么状态… 哈哈。 编写指令时一样