我有一个指令调用另一个指令将一些值作为对象传递。我的问题是模板在承诺获得数据之前被编译。
指令:
var directives = angular.module('app.directives', []);
directives.directive('mydirective', function (myService, $http, $compile) {
var templateUrl = "/some/file.html";
return {
restrict: "AE",
scope: {
entry: "="
},
link: function (scope, element, attrs) {
var entry = scope.entry;
var template = {
//** some empty key - value pairs **//
};
$http.get(templateUrl).then(function (response) {
element.html(response);
myService(entry.id, function (err, res) {
if (err)
throw err;
//** code to fill the template object **//
scope.seqplot = template;
$compile(element.contents())(scope);
});
});
}
};
});
模板(可以访问seqplot指令here):
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Some header
</h3>
</div>
<div class="panel-body">
<div class="row" ng-repeat="x in seqplot.k2 track by $index">
{{$index}}
<div class="col-md-4">
{{seqplot.k1[$index]}}
</div>
<div class="col-md-8">
<seqplot data-bar-width="666"
data-region-data="seqplot.k3"
data-regions='seqplot.k2[$index]'
data-seq="{{seqplot.k4}}"
data-gradient="true"></seqplot>
</div>
</div>
</div>
</div>
我称之为指令的部分:
<div>
<h1 class="page-header">{{entry.name| uppercase}} <small> - {{entry.uniprot_id| uppercase}}</small> </h1>
<div mydirective data-entry="entry"></div>
</div>
控制器:
var ctrlEntry = controllers.controller('ctrlEntry', function ($scope, $location, $rootScope) {
var getEntry = function (obj_arr, id) {
for (var i = 0; i < obj_arr.length; i++) {
var curr = obj_arr[i];
if (curr.id === id) {
return curr;
}
}
};
var data = $rootScope.data;
var path = $location.path().split('/');
var entry_id = path[path.length - 1];
$scope.entry = getEntry(data, entry_id);
});
问题是在执行myService回调之前,mydirective的scope.seqplot对象被传递给seqplot指令。因此我怀疑我需要一些方法在服务回调执行后立即重新编译html模板,或者让指令等待编译模板,直到服务回调完全执行。想法?非常感谢。
答案 0 :(得分:1)
初始化逻辑不属于指令链接功能。最好的情况是使用路由器(ngRoute / ui-router),它为您提供resolve
属性,在进入UI之前所有内容都已初始化,因此在编译指令之前所有数据都已准备就绪。