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 - angularjs的自定義過濾器如何給文字加顏色?2. angular.js - angular指令link事件綁定問題3. angular.js - Angular 2 + Django構建的Web應用, 如何合理搭配 ?4. angular.js - angularjs怎么從一個頁面向另一個頁面傳變量。5. angular.js - Angular1使用bootstrap輪播條carousel不能自動輪播6. angular.js - angular的ng-if表達式里面怎么 處理判斷條件??7. angular.js - angular post的Content-Type被設置,導致不能上傳圖片,求助!!8. angular.js - angularJs 在谷歌瀏覽器上面 輸入框輸入中文不能響應,但英文和字母可以,其他瀏覽器不存在這個問題9. angular.js - angular ng-class里面可以用 {{}} 取值嗎10. angular.js - AngularJS點擊搜索,實現數據變化,不通過重新請求接口的方法
