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 - angular2 属性组件与控件组件之间如何通信3. angular.js - angularjs 与requirejs集成4. angular.js - angular sortable 可以拖动但停止时位置无法发生变化5. angular.js - angular内容过长展开收起效果6. angular.js - angular js配置路由 编写控制器的时候说跳转页内的数据模型不存在7. angular.js - angularjs 修改入口文件 index.html 的位置8. angular.js - AngularJS 里 html中语法和 artTemplate 模板语法冲突 怎么破?9. angular.js - angular2 基础问题,求解答10. angular.js - angular如何在点击元素附近生成一个弹框,类似worktile点击弹出下拉框
