angular.js - angular,公共的代碼你們是放在哪里的
問題描述
我最開始是放在rootScope,發現這是全局屬性,就放棄了又不想在每個需要用到的controller里面都寫一遍,之后我選擇放入指令directive里面的controller里面,之后,我又發現,directive是依賴HTML的,如果方法一樣,但是我HTML不一樣,指令就沒辦法用來了。說得有點亂,我的意思是:我的一個方法所有的地方都可能用得到,我需要放在哪里?以后用得上的時候直接調用方法。比如:把它作為公共的代碼,應該怎么寫
問題解答
回答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))
相關文章:
1. angular.js - Angular路由和express路由的組合使用問題2. angular.js - angularjs 與requirejs集成3. angular.js - angularjs resizable控件4. angular.js - angularjs自定義指令作作用域觸發問題5. angular.js - angular如何實現以下布局..6. angular.js - angularjs的問題:點擊”選擇圖片“后,需要很長的時間才能選擇圖片7. angular.js - angularJs使用iframe,網頁內容自適應的問題8. angular.js - angularJS service里面存儲的數據能夠直接和HTML頁面交互嗎?9. angular.js - angularjs模塊加載10. angular.js - angular js配置路由 編寫控制器的時候說跳轉頁內的數據模型不存在
