【发布时间】:2012-10-31 17:17:30
【问题描述】:
我为以下小部件属性创建了一个自定义指令:
<div widget></div>
基本上,该指令只是创建一些模板代码并将 html 放入 widget-tag 中。 这是指令:
skdApp.directive("widget", function() {
return {
restrict: 'A',
template: htmlTemplate,
link: function($scope, element, attri) {
/*
* setup event handler and twitter bootstrap components here
*/
}
}
htmlTemplate 是基本的 html 代码,它也使用自定义指令(例如 <seal> 标签):
var htmlTemplate = '<div ng-controller="OfferCtrl">' +
'<div class="container">' +
<seal></seal>' +
'...'+
'</div>' +
'</div>';
在我的控制器中,我首先请求在
skdApp.controller('OfferCtrl', function OfferCtrl ($scope, Offer) {
var o = Offer.query({id: 1}, function (response) {
$scope.offer = response;
});
});
在响应处理程序中,我将结果绑定到范围。 我现在面临的问题是该指令也请求数据,但此请求取决于从 Offer.query() 接收到的数据。 IE。 Offer.query() 的响应返回一个 ID(我们称之为 myID),这是 seal 指令请求更多数据所必需的。 因此,我只是将我所有的逻辑都放在了回调 Offer.query 回调函数中。这似乎不是最好的方法。
所以我想把这部分移到<seal>指令的链接函数中:
skdApp.directive("seal", function() {
var sealHTML = '<div>{{offer.data.foobar}}</div>';
return {
restrict: 'E',
template: sealHTML,
link: function($scope, element, attrs) {
$scope.$watch('offer.myId', function (newValue, oldValue) {
if (typeof newValue !== "undefined") {
/* request more data with myId
* and bind the result to offer.data
*/
}
});
}
});
这种方法是否符合“角度”,或者是否有其他更好的方法(在结构方面)可以在角度上做到这一点?
【问题讨论】:
-
你将你的服务器交互封装到一个服务中,你的控制器很好而且“瘦”,你的指令 $watch()es 用于 $scope 更改以触发一些操作。我喜欢它。
标签: javascript angularjs directive