search

Home  >  Q&A  >  body text

angular.js - angular, where do you put the public code?

I initially put it in rootScope, and found that it was a global attribute, so I gave up.
I didn’t want to write it in every controller that needed to be used, so I chose to put it in the controller in the directive. Later, I discovered that directives depend on HTML. If the method is the same but my HTML is different, the directive cannot be used.
It’s a bit confusing. What I mean is: One of my methods may be used everywhere, where do I need to put it? Call the method directly when it is needed in the future.
For example: how to write it as public code

给我你的怀抱给我你的怀抱2866 days ago669

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-15 17:03:00

    Best to use service或者factory

    // use factory
    angular.module('YourAppName')
        .factory('YourFuncName', function() {
            return function() {
                // your function code here
            }
        });
        
    // use service
    angualr.module('YourAppName')
        .service('myUtils',function() {
            this.yourFuncName = function() {
                // your function code here
            }
        })

    For the situation in the screenshot

    angular.module('YourAppName')
        .factory('YourFuncName', function() {
            return function($scope) {
                return function(modal) {
                    // Use $scope Here
                }
            }
        });
        
    // 使用时
    somthing.then(yourFuncName($scope))

    reply
    0
  • Cancelreply