我知道有$viewContentLoaded
,但是在 AngularJS用占位符代替范围变量之前触发。
我设法通过在$viewContentLoaded
侦听器中设置0 ms的超时来解决此问题,但这非常难看。
我正在使用它来解析partials中包含的LessCSS样式表,但是我有一个URL前缀字段,在将它传递给LESS之前,我需要将其替换为样式表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');
};
[...]
这里有一个相关问题:How can I trigger an event when an angular JS route template has been loaded
我尝试使用$routeChangeSuccess
代替答案,但结果相同。
干杯
答案 0 :(得分:2)
这是一个非常长的线程,但它可能会对你有所帮助。从快速阅读,我认为这不是一个有角度的做事方式。相反,建议使用directive
来解决问题。
答案 1 :(得分:1)
根据Jess的回答,我采用了另一条路径并使用指令解决了它。
/**
* 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>