当观点在Angularjs呈现时,哪个事件会发射



我知道有 $viewContentLoaded,但是它在 angularjs之前触发用示波器变量代替了占位符。

我通过在$viewContentLoaded侦听器中设置0毫秒的超时来解决此问题,但这非常丑陋。

我正在用它来解析partials中包含的liesscss样式表,但是我有一个URL前缀字段,我需要在将其替换为stylesheet url之前。

这是我的代码(带有丑陋的黑客):

var AccountController = function($scope, UserService) {
    var user = UserService.get();
    $scope.username = user.profile.displayName || user.contact;
    var bindLESSInit = function($scope, linkElementSelector) {
        $scope.$on('$viewContentLoaded', function() {
            var linkElement = document.querySelector(linkElementSelector);
            if (!linkElement) throw new Error('bindLESSInit: link element not found');
            console.log('link href before timeout: ', linkElement.href);
            // BAD: outputs "http://localhost:8282/%5B%5BstaticURLPrefix%5D%5D/static/portal/app/less/account.less"
            setTimeout(function() {
                console.log('link href after timeout: ', linkElement.href);
                // GOOD: outputs "http://localhost:8282/static/portal/app/less/account.less"
                // clear previous view's styles
                less.sheets = less.sheets.filter(function(e) { 
                    return e.getAttribute('class') && e.getAttribute('class').match('view-style');
                });
                less.sheets.push(linkElement);
                less.refresh();   
            }, 0);
        });
    };
    bindLESSInit($scope, '#account-stylesheet');    
};
[...]

这里有一个相关的问题:当已加载Angular JS路由模板时,如何触发事件

我尝试了答案,而是使用$routeChangeSuccess,但给出了相同的结果。

欢呼

这是一个很长的线程,但可能会对您有所帮助。从快速阅读中,我认为这不是做事的角度方式。相反,建议使用directive解决问题。

https://github.com/angular/angular.js/issues/734

基于杰西的答案,我走了另一条路径并使用指令解决了。

/**
 * Directive to load LESS stylesheets when inserted.
 * @param {attribute} url url of the stylesheet
 */
var lessStylesheetDirective = function() {
    var link = function(scope, element, attrs) {        
        var linkElement = $('<link rel="stylesheet/less" type="text/css">');
        // when link is called, we don't have the attribute yet, if it's interpolated.
        // see http://stackoverflow.com/questions/11913841
        attrs.$observe('url', function(value) {
            if (!value) return;
            if (!window.less) throw new error('LESS global not found!');  
            linkElement.href = value;
            less.sheets.push(linkElement);
            // we reload everything FIXME: can we reload only this one?
            less.refresh(); 
        });
        element.on('$destroy', function() {
            // we remove our style from less, so it won't be parsed again
            less.sheets = less.sheets.filter(function(e) { 
                return e !== linkElement;
            });
        });
    };
    return {
        link: link,
    }
};
app.directive('lessStylesheet', lessStylesheetDirective);

用法:

<div less-stylesheet url="{{yourUrlComesHere}}"></div>

最新更新