前端開發框架總結之Angular實用技巧(五)
阿新 • • 發佈:2018-11-12
前端開發框架總結之Angular實用技巧(五)
上文講了Angular中網路請求相關的知識,掌握了這些,我們就可以在前端與後臺進行通訊了,這樣可以實現複雜的業務功能了。今天我們再來介紹下angular 依賴注入相關的知識。
- angular 依賴注入
依賴注入的寫法一共有三種
第一種
app.add.controller('manageCtrl', ['$scope','$rootScope', '$state','$http',function ($scope, $rootScope,$state,$http) { }]);
第二種
app.add.controller('manageCtrl',function ($scope, $rootScope,$state,$http) {
});
第三種
app.add.controller('manageCtrl',manageCtrl) {
}]);
function manageCtrl($scope, $rootScope,$state,$http){
}
manageCtrl.$inject = [$scope, $rootScope,$state,$http];
其中第二種寫法在程式碼混淆時會出錯。
-
載入順序
constant---->provider---->config---->value---->factory---->service----->run---->directive---->controller;
其中factory,service,directive是有使用的時候才會載入。
-
自定義服務
自定義服務的方法有三種,factory、service、provider。每種定義的語法不同,但是作用一樣。其中provider比較特殊,他可以注入到config函式。這個從上邊的載入順序就可以看出來。
具體每種的寫法如下:
<script>
var app = angular.module('ExampleApp', []);
app.config(['myConstants',function (myConstants) {
console.log('enter config function1');
console.log("myConstants.aaa:" + myConstants.aaa);
}]);
app.run(['myValues','myFactory','myService','myProvider','$rootScope',function (myValues,myFactory,myService,myProvider,$rootScope) {
console.log('enter run function');
console.log("myValues.bbb:" + myValues.bbb);
console.log("myFactory.fff:" + myFactory.fff);
console.log("myService.ddd:" + myService.ddd);
console.log("myProvider.eee:" + myProvider.eee);
$rootScope.globalVar = 'rootScope的全域性變數';
}]);
app.config(['myProviderProvider',function (myProviderProvider) {
console.log('enter config function2');
console.log("myProviderProvider.eee:" + myProviderProvider.eee);
myProviderProvider.eee = 'eee變化';
}]);
app.constant('myConstants',{
aaa:'aaa初值'
});
app.value('myValues',{
bbb:'bbb初值'
});
app.controller('testCtrl',['$scope','myProvider', function ($scope,myProvider) {
console.log('enter control function');
$scope.inputValue = '初值';
console.log("myProvider.eee:" + myProvider.eee);
console.log("rootScope.globalVar:" + $scope.globalVar);
}]);
app.factory('myFactory',function () {
console.log('enter myFactory');
var myFactory = {};
myFactory.fff = 'myFactory fff初始值';
return myFactory;
});
app.service('myService',function () {
console.log('enter myService');
this.ddd = 'ddd初值';
});
app.provider('myProvider',function (myConstants) {
console.log('enter myProvider');
this.eee = 'eee初值';
console.log("myProvider,myConstants.aaa:" + myConstants.aaa);
this.$get = function () {
var that = this;
return {
eee: that.eee
}
}
});
app.directive('myDirective',function () {
console.log('enter myDirective');
return {
restrict: 'A',
require: '?^ngModel',
}
})
</script>
-
全域性變數
實現全域性變數的方式有如下幾種:constant、value、$rootScope、通過var定義全域性變數(原生js語法)、通過service共享變數。
其中constant可以在config中注入,value不可以,$rootScope也不可以。他們都可以在run及以後使用。