gpt4 book ai didi

javascript - 在设置属性之前加载指令

转载 作者:行者123 更新时间:2023-11-29 19:39:56 24 4
gpt4 key购买 nike

我有一个如下所示的指令

   app.directive("responses", function ()
{
return {
templateUrl: "/templates/responses.html",

link: function(scope, element, attrs, parentCtrl)
{
var type = attrs.type;
}
}
});

这是 html 标记中的指令。 type 属性由 Controller 设置。它是 $http 调用的结果

<div responses type="{{Data.Type}}"></div>

但是,当指令去检索这个属性时,它还没有被父 Controller 设置。所以当指令加载时,type 最终被设置为空。我想我可以用 setInterval() 来解决,但这似乎不是最好的方法。有什么想法吗?

这是简化的 Controller

   controllers.AppCtrl = function($scope, $routeParams, $http)
{
$scope.Data ={
Type = ""
}

$http.get("http://restfulURI/3").success(function (result)
{
$scope.Data.Type = result.Type;
}
}

最佳答案

尝试使用 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 将在 attribute property 上添加一个监听器事件,一旦它发生变化,它将在您的指令上触发该事件。

这里是 plunker demo

关于javascript - 在设置属性之前加载指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23764859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com