angular.js - angular,公共的代碼你們是放在哪里的
問題描述
我最開始是放在rootScope,發(fā)現(xiàn)這是全局屬性,就放棄了又不想在每個需要用到的controller里面都寫一遍,之后我選擇放入指令directive里面的controller里面,之后,我又發(fā)現(xiàn),directive是依賴HTML的,如果方法一樣,但是我HTML不一樣,指令就沒辦法用來了。說得有點亂,我的意思是:我的一個方法所有的地方都可能用得到,我需要放在哪里?以后用得上的時候直接調(diào)用方法。比如:把它作為公共的代碼,應(yīng)該怎么寫
問題解答
回答1:最好用service或者factory
// use factoryangular.module(’YourAppName’) .factory(’YourFuncName’, function() {return function() { // your function code here} }); // use serviceangualr.module(’YourAppName’) .service(’myUtils’,function() {this.yourFuncName = function() { // your function code here} })
對于截圖中的情況
angular.module(’YourAppName’) .factory(’YourFuncName’, function() {return function($scope) { return function(modal) {// Use $scope Here }} }); // 使用時somthing.then(yourFuncName($scope))
相關(guān)文章:
1. angular.js - angularjs如何動態(tài)改變ng-model值,在controller中獲取input中輸入的值并組合post發(fā)送到后臺2. angular.js - angular如何在點擊元素附近生成一個彈框,類似worktile點擊彈出下拉框3. angular.js - angular登錄完成后,如何正確在header顯示用戶數(shù)據(jù)4. angular.js - angular route如何實現(xiàn)單頁面切換時數(shù)據(jù)的傳遞5. angular.js - angularjs 用ng-reapt渲染的dom 怎么獲取上面的屬性6. angular.js - angularjs自定義指令作作用域觸發(fā)問題7. angular.js - angularjs resizable控件8. angular.js - angular $interval怎么在一個按鈕上實現(xiàn)開始定時和結(jié)束定時9. angular.js - angular-ueditor使用中,插入圖片,加載完成后不更新angularmodel的問題;10. angular.js - angularjs 修改入口文件 index.html 的位置
