我的指令类似于以下
app.directive("responses", function ()
{
return {
templateUrl: "/templates/responses.html",
link: function(scope, element, attrs, parentCtrl)
{
var type = attrs.type;
}
}
});
这是html标记中的指令。 type
属性由控制器设置。这是$http
电话
<div responses type="{{Data.Type}}"></div>
但是,当指令转到检索此属性时,父控制器尚未设置它。因此,当指令加载时,type
最终设置为空。我想我可以用setInterval()
来解决,但这似乎不是最好的方法。有什么想法吗?
这是简化的控制器
controllers.AppCtrl = function($scope, $routeParams, $http)
{
$scope.Data ={
Type = ""
}
$http.get("http://restfulURI/3").success(function (result)
{
$scope.Data.Type = result.Type;
}
}
答案 0 :(得分:2)
尝试使用scope.$watch
代替:
app.directive("responses",function(){
return {
templateUrl: "/templates/responses.html",
link: function(scope, element, attrs, parentCtrl){
scope.$watch(attrs.type,function(newvalue,oldvalue){
//on attribute value changes
});
}
}
});
$watch
将在属性属性上添加一个侦听器事件,一旦更改,它将触发指令上的事件。
答案 1 :(得分:1)
如果要在属性更改时启动某些特殊操作,则需要使用观察程序 此外,如果您不使用隔离范围,那么观察属性没有太大意义,因为您可以访问控制器范围,无论如何您只需要观察Data.Type更改。为了提供更好的解决方案,我们需要了解有关最终应用程序的更多信息以及您希望实现的目标。