angular.js - angular,公共的代碼你們是放在哪里的
問(wèn)題描述
我最開(kāi)始是放在rootScope,發(fā)現(xiàn)這是全局屬性,就放棄了又不想在每個(gè)需要用到的controller里面都寫(xiě)一遍,之后我選擇放入指令directive里面的controller里面,之后,我又發(fā)現(xiàn),directive是依賴HTML的,如果方法一樣,但是我HTML不一樣,指令就沒(méi)辦法用來(lái)了。說(shuō)得有點(diǎn)亂,我的意思是:我的一個(gè)方法所有的地方都可能用得到,我需要放在哪里?以后用得上的時(shí)候直接調(diào)用方法。比如:把它作為公共的代碼,應(yīng)該怎么寫(xiě)
問(wèn)題解答
回答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} })
對(duì)于截圖中的情況
angular.module(’YourAppName’) .factory(’YourFuncName’, function() {return function($scope) { return function(modal) {// Use $scope Here }} }); // 使用時(shí)somthing.then(yourFuncName($scope))
相關(guān)文章:
1. angular.js - angularjs的自定義過(guò)濾器如何給文字加顏色?2. angular.js - angular內(nèi)容過(guò)長(zhǎng)展開(kāi)收起效果3. angular.js - angularjs 百度統(tǒng)計(jì)怎么統(tǒng)計(jì)4. angular.js - angularjs中自定義指令scope的問(wèn)題5. angular.js - angular2中異步ngfor渲染數(shù)據(jù)的bug?6. angular.js - angular.ui:dropdown的下拉菜單關(guān)閉的偶爾失常問(wèn)題7. angular.js - angular指令link事件綁定問(wèn)題8. angular.js - AngularJs ng-repeat指令 如何取Json對(duì)象渲染到前端模板?9. angular.js - angularjs $resource發(fā)出的post請(qǐng)求如何詳細(xì)設(shè)置?10. angular.js - angularjs項(xiàng)目使用grunt serve運(yùn)行報(bào)錯(cuò)

網(wǎng)公網(wǎng)安備