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 post的Content-Type被设置,导致不能上传图片,求助!!2. angular.js - angularjs的自定义过滤器如何给文字加颜色?3. angular.js - angularjs scope.$watch取不到input变化的值4. angular.js - Angular 像这种重复判断的表达式 有什么好的解决办法吗?~5. angular.js - angularjs改变路由时控制器每次都执行两次?6. angular.js - AngularJS点击搜索,实现数据变化7. angular.js - angularjs resizable控件8. angular.js - angular 报错9. angular.js - angular2 修改form表单10. angular.js - angular使用ng-include,为什么生成不了html代码

网公网安备