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的ui-router的$stateChangeStart事件沒有觸發。是寫法有問題嗎2. angular.js - angularjs不同標簽頁切換 ui-view,且不 刷新頁面3. angular.js - angularjs動態增加DOM4. angular.js - angularjs scope.$watch取不到input變化的值5. angular.js - AngularJs ng-repeat指令 如何取Json對象渲染到前端模板?6. angular.js - angularjs requirejs karma directive templateUrl 測試失敗(哎呦喂)7. angular.js - angularjs中如何實現單擊一個span標簽之后,拿到span標簽中的內容?8. angular.js - AngularJS 中如何給一個自定義指令 directive 傳遞一個對象類型的參數?9. angular.js - angular TypeError: Cannot read property ’id’ of undefined?10. angular.js - angularjs ng-repeat 不能刷新
