我的指令变得越来越复杂。所以我决定把它分成几部分。
该指令本身加载了服装SVG图形,当SVG加载它时,然后运行一个配置方法,该方法将应用设计,应用拾取的颜色(或编辑时的数据库颜色)和其他零碎。
正如我所说,这一切都在一个指令中,但我现在决定将逻辑分开。 所以我创建了我的第一个指令:
.directive('configurator', function () {
// Swap around the front or back of the garment
var changeView = function (element, orientation) {
// If we are viewing the front
if (orientation) {
// We are viewing the front
element.addClass('front').removeClass('back');
} else {
// Otherwise, we are viewing the back
element.addClass('back').removeClass('front');
}
};
return {
restrict: 'A',
scope: {
garment: '=',
onComplete: '&'
},
require: ['configuratorDesigns'],
transclude: true,
templateUrl: '/assets/tpl/directives/kit.html',
link: function (scope, element, attrs, controllers) {
// Configure our private properties
var readonly = attrs.hasOwnProperty('readonly') || false;
// Configure our scope properties
scope.viewFront = true;
scope.controls = attrs.hasOwnProperty('controls') || false;
scope.svgPath = 'assets/garments/' + scope.garment.slug + '.svg';
// Apply the front class to our element
element.addClass('front').removeClass('back');
// Swaps the design from front to back and visa versa
scope.rotate = function () {
// Change the orientation
scope.viewFront = !scope.viewFront;
// Change our view
changeView(element, scope.viewFront);
};
// Executes after the svg has loaded
scope.loaded = function () {
// Call the callback function
scope.onComplete();
};
}
};
})
这在设计上非常简单,它可以获得服装并找到正确的SVG文件并使用ng-transclude加载它。 一旦文件加载,就会调用一个回调函数,这只是告诉视图它已经完成加载。
你应该能够解决一些其他的问题(改变观点等)。
在这个例子中,我只需要另外一个指令,但是在项目中有3个必需的指令,但是为了避免复杂化,可以用来证明我的问题。
我的第二个指令是应用设计所需要的。它看起来像这样:
.directive('configuratorDesigns', function () {
return {
restrict: 'A',
controller: 'ConfiguratorDesignsDirectiveController',
link: function (scope, element, attrs, controller) {
// Get our private properties
var garment = scope.$eval(attrs.garment),
designs = scope.$eval(attrs.configuratorDesigns);
// Set our controller designs array
controller.designs = designs;
// If our design has been set, watch it for changes
scope.$watch(function () {
// Return our design
return garment.design;
}, function (design) {
// If we have a design
if (design) {
// Change our design
controller.showDesign(element, garment);
}
});
}
}
})
该指令的控制器只是循环通过SVG并找到与服装设计对象匹配的设计。如果它找到它,它只是隐藏其他人并显示一个。 我遇到的问题是该指令不知道SVG加载与否。在"父母"指令我有scope.loaded函数,它在SVG加载完成后执行。 "父母"指令的模板如下所示:
<div ng-transclude></div>
<div ng-include="svgPath" onload="loaded()"></div>
<a href="" ng-click="rotate()" ng-if="controls"><span class="glyphicon glyphicon-refresh"></span></a>
所以我的问题是: 如何获取所需的指令以了解SVG加载状态?
答案 0 :(得分:1)
如果我理解你的问题,$ rootScope.broadcast应该会帮助你。只需在加载完成时进行广播。从正在加载图像的指令发布消息。在需要知道加载完成的指令上,监听消息。