0

I have the following situation, I use a jQuery preload plugin.

angular.module('app')
    .factory('Preloader', function Preloader(Videos) {


        return {
            start: function() {

                $.html5Loader({
                    filesToLoad: Videos.query(),
                    onBeforeLoad: function() {},
                    onComplete: function() {
                      //$scope.loaded = done
                    },
                    onElementLoaded: function(obj, elm) {},
                    onUpdate: function(percentage) {
                      //$scope.precentage = precentage
                    }
                });

            }
        }

    });

I build a factory where I wrap the plugin.

In my controller I have something like:

angular.module('playlist')
    .controller('Ctrl', function($scope, Preloader, Videos) {

        Preloader.start();        

And on the HTML I have a loading screen which I want to hide with ng-if="!loaded".

Can someone explain me how to link the $scope.loaded from the factory to the $scope.loaded inside my controller?

2
  • suggest you put that code in a directive which already exposes scope. Commented Oct 12, 2015 at 11:32
  • $scope in Angular is always associated with an HTML view. Factories/services are not associated with any views, and therefore do not get a $scope injected into them like a controller would. Services/factories can have the $rootScope injected into them. You can put things on the $rootScope or better use a directive like suggested above to access a specific $scope. Commented Oct 12, 2015 at 11:34

1 Answer 1

2

Directive is the right way to go in this case and not factory. This way, you can expose the loaded variable using the directive $scope.

If you would like to use factory anyway, expose the loaded variable as a member of the factory so you can watch for changes in the controller.

EDIT

To call start you can use events or two-way binding (which is my favorite)

Sign up to request clarification or add additional context in comments.

7 Comments

But how can I start the preload like I do now in my directive? Now I have Preloader.start();
Sorry, can you detail a little bit more? If I make a directive and I use link function, the preload will start when the page is loaded?
the link function is called when the element is attached to the DOM
jsbin.com/turuwotuda/1/edit?html,js,output, I have problem I have this link: function(scope) {} but when I put {{percentage}} on my HTML its not updating
jsbin.com/rogemucini/edit?html,js,output Check this out, Its not all the code, but I the thing is that {{loaded}} or {{percentage}} are not being displayed in the HTML, and not updating
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.