我有一个父状态,在其解析中加载一个JavaScript文件(比如abc.js)。所有子状态的控制器都在该abc.js文件中定义。很明显,我希望在父完成加载abc.js之后解决所有子状态。请在下面找到我的代码段 -
.state('parent', {
url: '/role',
templateUrl: 'something.tmpl.html',
resolve: {
loadRoleScript: function() {
var injector = angular.injector(['ng']),
q = injector.get('$q'),
deferred = q.defer(),
scriptTag = '';
scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = 'path/to/js/file/abc.js';
scriptTag.onload = scriptTag.onreadystatechange = function(_, isAbort) {
if (!scriptTag.readyState || /loaded|complete/.test(scriptTag.readyState)) {
if (isAbort) {
deferred.reject();
} else {
setTimeout(function() {
// Here goes some of my logic
console.log('Parent resolved');
deferred.resolve();
}, 100);
}
}
};
scriptTag.onerror = function() {
deferred.reject();
};
document.body.appendChild(scriptTag);
}
}
})
.state('parent.dashboard', {
url: '/roledashboard',
controller: 'RoleHomeCtrl',
templateUrl: 'something/child.tmpl.html',
resolve: {
dependent1: ['loadRoleScript', function(loadRoleScript) {
console.log('child getting loaded before parent is resolved');
}]
}
});
输出我正在使用控制台 -
在解析父项之前加载子项。
家长解决了。
我已经按照这样的多个链接 - https://github.com/angular-ui/ui-router/issues/1903 但是到处建议的解决方案并不适用于我。
$ ocLazyLoad也是一个选项,但试图自己实现。
提前致谢!
答案 0 :(得分:1)
我认为你需要修改你的代码:
.state('parent', {
url: '/role',
templateUrl: 'something.tmpl.html',
resolve: {
loadRoleScript: function() {
var injector = angular.injector(['ng']),
q = injector.get('$q'),
deferred = q.defer(),
scriptTag = '';
scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.src = 'path/to/js/file/abc.js';
scriptTag.onload = scriptTag.onreadystatechange = function(_, isAbort) {
if (!scriptTag.readyState || /loaded|complete/.test(scriptTag.readyState)) {
if (isAbort) {
deferred.reject();
} else {
setTimeout(function() {
// Here goes some of my logic
console.log('Parent resolved');
deferred.resolve();
}, 100);
}
}
};
scriptTag.onerror = function() {
deferred.reject();
};
document.body.appendChild(scriptTag);
// !!
// !!
return deferred.promise;
// !!
// !!
}
}
})
.state('dashboard', {
parent:'parent',
url: '/roledashboard',
controller: 'RoleHomeCtrl',
templateUrl: 'something/child.tmpl.html',
resolve: {
dependent1: function(loadRoleScript) {
console.log('child getting loaded before parent is resolved');
}
}
});
然后应该正确解析父状态