Javascript 在设置属性之前加载指令
我有一个如下的指令Javascript 在设置属性之前加载指令,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有一个如下的指令 app.directive("responses", function () { return { templateUrl: "/templates/responses.html", link: function(scope, element, attrs, parentCtrl) { var type = attrs.type; } } }); 下面是ht
app.directive("responses", function ()
{
return {
templateUrl: "/templates/responses.html",
link: function(scope, element, attrs, parentCtrl)
{
var type = attrs.type;
}
}
});
下面是html标记中的指令。类型
属性由控制器设置。它是一个$http
调用的结果
<div responses type="{{Data.Type}}"></div>
尝试使用
范围。$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
将在属性属性上添加侦听器事件,一旦它更改,将触发指令上的事件
以下是如果要在属性更改时启动某些特殊操作,则需要使用观察程序
另外,如果您不使用独立作用域,那么查看属性也没有多大意义,因为您可以访问控制器作用域,您可以只查看数据。类型更改。为了提供更好的解决方案,我们需要更多地了解最终应用以及您希望实现的目标。数据是否来自角度范围之外?是的。它是由$http调用生成的。您的视图可能没有更新,因为当数据更改或加载时,它不会导致运行$digest循环。您能在加载数据的地方添加控制器代码吗?好的。添加了控制器代码尝试将.success更改为.then,看看这是否解决了问题。我尝试添加了$watch,就像您的示例中一样,但attrs.type、oldvalue和newvalue都未定义。我是否需要以某种方式在指令本身上定义作用域?第一次我猜它是未定义的,但是如果您设置了数据。在控制器中键入某个内容,它应该反映出这一点!检查了你的plunker演示。事实证明,问题的根源在于属性“type”周围有两个大括号。将其更改为type=“Data.type”解决了该问题。谢谢
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
});
}
}
});