指令在属性设置之前加载

Directive loads before attributes are set

本文关键字:加载 设置 属性 指令      更新时间:2023-09-26

我有一个指令,看起来像下面的

   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;
          }
    }

尝试使用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将在属性属性上添加一个监听事件,一旦它改变,它将触发你指令上的事件。

这是活塞演示

如果您想在属性更改时启动一些特殊操作,则需要使用监视器此外,如果您不使用隔离作用域,那么监视属性也没有多大意义,因为您可以访问控制器作用域,无论如何您都可以监视Data。类型发生变化。为了提供更好的解决方案,我们需要更多地了解最终应用程序以及您想要实现的目标。