How to delay running logic for directive until ui-route is resolved?

£可爱£侵袭症+ 提交于 2019-12-11 18:37:35

问题


I am using AngularJS with ui-router. I am attempting to make use of the AngularJS PDF directive available at https://github.com/sayanee/angularjs-pdf. I'm having to make some changes to the example given because I do not have the URL to the PDF right off the bat.

However, I ran into a problem. Because I pass an id value associated with the PDF into the route, I have to wait to resolve that parameter until the route change has been successful. I accomplished this with the guidance at https://github.com/angular-ui/ui-router/wiki under the Resolve section.

But, when, I visit the page, before any of this is resolved, and before I make the query to the API with this ID so as to resolve the URL of the file, I find myself clicking through the directive. Of course, I haven't populated the scope of the directive with the values since the route hasn't returned the resolve promise yet, so this is a null value, that ultimately give me an error in pdf.js that the url isn't populated.

How can I delay executing the logic within the directive until the scope has been appropriately populated as I require?

So you don't have to download the directive I linked at the top, here's what I'm working with:

(function () {

    'use strict';

    angular.module('pdf', []).directive('ngPdf', function ($window) {
        return {
            restrict: 'E',
            templateUrl: function (element, attr) {
                return attr.templateUrl ? attr.templateUrl : 'viewer.html';
            },
            link: function (scope, element, attrs) {
                var url = scope.pdfUrl,
                  pdfDoc = null,
                  pageNum = 1,
                  scale = (attrs.scale ? attrs.scale : 1),
                  canvas = (attrs.canvasid ? document.getElementById(attrs.canvasid) : document.getElementById('pdf-canvas')),
                  ctx = canvas.getContext('2d'),
                  windowEl = angular.element($window);

                windowEl.on('scroll', function () {
                    scope.$apply(function () {
                        scope.scroll = windowEl[0].scrollY;
                    });
                });

                PDFJS.disableWorker = true;
                scope.pageNum = pageNum;

                scope.renderPage = function (num) {

                    pdfDoc.getPage(num).then(function (page) {
                        var viewport = page.getViewport(scale);
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;

                        var renderContext = {
                            canvasContext: ctx,
                            viewport: viewport
                        };

                        page.render(renderContext);

                    });

                };

                scope.goPrevious = function () {
                    if (scope.pageNum <= 1)
                        return;
                    scope.pageNum = parseInt(scope.pageNum, 10) - 1;
                };

                scope.goNext = function () {
                    if (scope.pageNum >= pdfDoc.numPages)
                        return;
                    scope.pageNum = parseInt(scope.pageNum, 10) + 1;
                };

                scope.zoomIn = function () {
                    scale = parseFloat(scale) + 0.2;
                    scope.renderPage(scope.pageNum);
                    return scale;
                };

                scope.zoomOut = function () {
                    scale = parseFloat(scale) - 0.2;
                    scope.renderPage(scope.pageNum);
                    return scale;
                };

                scope.changePage = function () {
                    scope.renderPage(scope.pageNum);
                };

                scope.rotate = function () {
                    if (canvas.getAttribute('class') === 'rotate0') {
                        canvas.setAttribute('class', 'rotate90');
                    } else if (canvas.getAttribute('class') === 'rotate90') {
                        canvas.setAttribute('class', 'rotate180');
                    } else if (canvas.getAttribute('class') === 'rotate180') {
                        canvas.setAttribute('class', 'rotate270');
                    } else {
                        canvas.setAttribute('class', 'rotate0');
                    }
                };

                PDFJS.getDocument(url).then(function (_pdfDoc) {
                    pdfDoc = _pdfDoc;
                    scope.renderPage(scope.pageNum);

                    scope.$apply(function () {
                        scope.pageCount = _pdfDoc.numPages;
                    });
                });

                scope.$watch('pageNum', function (newVal) {
                    if (pdfDoc !== null)
                        scope.renderPage(newVal);
                });

            }
        };
    });

})();

Though I don't think it's particularly necessary, here's the simplified view of my controller:

angular.module('myApp').controller('myController', function($scope, $http, $state) {
 var url = "http://example.com/myService";
 $http.get(url)
  .success(function(data, status, headers, config) {
    $scope.pdfUrl = data.url;
    $scope.pdfName = data.name;
    $scope.scroll = 0;
    $scope.getNavStyle = function(scroll) {
      if (scroll > 100) return 'pdf-controls fixed';
      else return 'pdf-controls';
    }
  })
  .error(function(data, status, headers, config) {
    $state.go('failure.state');
  });
});

The ui-view looks like the following:

<ng-pdf template-url="pathToTemplate/viewer.html" canvasid="pdf" scale="1.5"></ng-pdf>

Thanks!


回答1:


It looks like you need to use the ui-router resolve feature to get the pdfUrl before the controller is loaded. For example, instead of using $http inside your controller, you should be returning the result of the $http call to the routes resolve function, allowing you to set the scope on controller initialisation. This is a basic example (will not work as written) to get you started:

Service:

angular.module('myApp', [])
.factory('PdfService', ['$http', function($http){
        return {
            getURL: function(id){
                // return promise from http
                return $http(urlWithProvidedId).then(function(result){
                    // return all necessary result data as object to be injected
                    return {
                        url: result.data.url
                    };
                });    
            }
        };
    }]);    

Then inside your route config:

.state('somestate', { controller: 'myController', templateUrl: 'sometemplate.html',
    resolve: { _pdfData: ['PdfService', '$stateParams', function(PdfService, $stateParams) {                                
        return PdfService.getURL($stateParams.whateverThePdfIdIs);                              
    }]}});

Then inject the result into your controller

.controller('myController', ['$scope', '_pdfData', function($scope, _pdfData){
    // set the pdf url
    $scope.pdfUrl = _pdfData.url;
}]);

Also, I want to mention that the directive you posted is quite poorly designed from an angular-way point of view, which likely plays into the difficulties you are having.



来源:https://stackoverflow.com/questions/24420144/how-to-delay-running-logic-for-directive-until-ui-route-is-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!