rit*_*der 18 javascript angularjs
我正在使用angularjs,我希望能够在需要时加载指令,而不是在页面开头加载所有指令.我正在尝试为我最常用的插件创建指令.
这样,一个direct可以用来yepnope在最终编译html之前加载所有需要的指令.
如果指令是在页面的开头与其他指令一起加载的,那么一切正常.但是,如果稍后加载'child'指令(在'parent'中),它将不会生效.下面是'parent'指令的compile字段中pre字段的代码.
...
var pre = function (scope, element, attrs) {
element.html('Please wait. Loading...');
ang.loadDirectives('caiDatePicker', function () {
console.log('loaded');
scope.data.raw = scope.rawData;
var html = createObjUi(scope, scope.data, scope.defn);
element.html(html); //data
$compile(element.contents())(scope.$new());
scope.$apply();
});
};
return { restrict:'A', compile: {pre:pre,post:function(){...}};
Run Code Online (Sandbox Code Playgroud)
ang.loadDirectives使用yepnope加载指令.'child'指令的部分代码如下:
angular.module('mycomponents') //PS: I'm assuming this will fetch the already created module in the 'parent' directive
.directive('caiDatePicker', function ($parse) {
return {
scope: {},
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch('this.$parent.editing', function (v) {
scope.editing = v;
});
yepnope({
test: $().datePicker,
nope: [
'/content/plugins/datepicker/datepicker.js', //todo: use the loader
'/content/plugins/datepicker/datepicker.css'
],
complete: function () {
if (scope.model && scope.model.value) {
var date = scope.model.value;
element.val(date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear());
}
element.datepicker({ weekStart: 1, format: 'dd/mm/yyyy' })
.on('changeDate', function (ev) {
scope.model.value = ev.date;
scope.$apply();
});
}
});
attrs.$observe('path', function (v) {
var fn = $parse(v);
var model = fn(scope.$parent);
scope.model = model;
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
我首先做的是什么?
如果是这样,我做错了什么?
ify*_*.io 17
如果要注册指令,则在引导应用程序之后,您将不得不使用$ compileProvider而不是模块API.例如...
$compileProvider.directive('SomeLazyDirective', function()
{
return {
restrict: 'A',
templateUrl: 'templates/some-lazy-directive.html'
}
})
Run Code Online (Sandbox Code Playgroud)
然后,在使用$ routeProvider定义路由时,可以使用'resolve'函数来使用脚本加载器加载惰性指令.为此,让函数返回一个在加载了指令和其他惰性依赖项后解析的promise.AngularJS将在呈现路由之前等待承诺得到解决,从而确保您的指令在视图需要之前就已准备就绪.我写了一篇博文,详细介绍了如何在AngularJS中实现延迟加载.它更详细地描述了我在这里所说的内容,可以在http://ify.io/lazy-loading-in-angularjs/找到它.
Kel*_*Kel 12
这是我所做的,使用附加到应用程序的编译提供程序,使其可以从具有实际模块引用的任何地方访问.
var app = angular.module('app');
app.config(function ($compileProvider) {
app.compileProvider = $compileProvider;
});
然后,在bootstrap之后,你可以懒洋洋地加载一个被编译和链接的指令:
app.compileProvider.directive('SomeLazyDirective', function()
{
return {
restrict: 'A',
templateUrl: 'templates/some-lazy-directive.html'
}
})
经过长时间的搜索并没有得到任何答案,我最终得到了以下结果
问题是 yepnope 没有像我需要的那样触发完整的函数。最后,我在 yepnope 之上构建了一个小包装器,它似乎可以保证完整的函数被触发。
最终代码如下所示:
var app3 = new Cai.AngApp('app3');
app3.loadControllers('app1.controller3', function () {
app3.loadDirectives('jsonEditor', 'datePicker', function () {
app3.bootstrap($('#d3'));
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15404 次 |
| 最近记录: |