3

我在AngularJS中盯着我。AngularJS等待範圍變量從自定義指令進行評估

我創建了一個自定義的指令:

app.directive('myScroll',function(){ 
return { 
    restrict: 'A', 
    transclude: true, 

    template: '<div ng-transclude></div>', 
    link: function(scope , element , attrs) { 

    element.addClass('scroll-pane'); 

    scope.$watch('tasks', function(newval, oldval){ 
      if (newval ) 
      { 

      console.log(newval); 
      console.log(newval.length); 
     } 

    }); 

     console.log("afer watch exper"); 
     console.log (tasks); 



    } 


    }; 

});

具有以下HTML:

<div my-scroll> 
     <ul> 
      <li data-ng-repeat="task in tasks" class="task-wrapper"> 
       <div class="task-element"> 
        <div class="name">{{task.name}}</div> 
        <div class="text">{{task.action}}</div> 
       </div> 
      </li> 
     </ul> 
    </div> 

任務目的是通過一個由控制器調用的服務進行評估(如果必要的話,我將發佈它的代碼)。

在指令代碼中,任務對象是未定義的,因爲我必須獲得執行更多css命令的任務長度,所以我必須等待ng-repeat完成或者只是等待任務變量纔會被評估。

由於某些原因,任務總是在$ watch語句的外部和內部都未定義。 我可以在控制檯中看到「先看看exper」之後先打印,然後看到「仍然沒有數值」。 newval對象具有[move2:function],但其length屬性保持返回0,但它保留了我的任務的資源數組。

我在這裏缺少什麼以及如何在任務變量被評估時執行命令?

感謝幫手。

回答

11

您應該使用scope.tasks來引用數據。

app = angular.module('myApp', []); 
app.directive('myScroll', function() { 
    return { 
     restrict: 'A', 
     transclude: true, 

     template: '<div ng-transclude></div>', 
     link: function (scope, element, attrs) { 

      element.addClass('scroll-pane'); 

      scope.$watch('tasks', function (newval, oldval) { 
       if (newval) { 
        console.log(newval); 
        console.log(newval.length); 
       } 
      }); 
      console.log("afer watch exper"); 
      console.log(scope.tasks); //this will log the actual data. 
     } 
    }; 
}); 

function Ctrl($scope) { 
    $scope.tasks = [{ 
     name: "task1", 
     action: "action1" 
    }] 
} 
+0

謝謝!我的愚蠢的錯誤...我還有一個小問題,我可以看到手錶表達被稱爲兩次,爲什麼?因爲asyc服務調用db? – RonenIL

5

嘗試的第三個參數傳遞 - 真正至$看:

scope.$watch('tasks', function(newval, oldval){ 
    if(newval){ 
     console.log(newval); 
     console.log(newval.length); 
    } 
},true); 
+0

這對我來說很有效,從文檔中我看到,在對象相等而不是引用上傳遞'true'力的比較。你知道爲什麼這裏需要嗎? – thebenedict

+1

當您將true作爲第三個參數傳遞時,angular會創建正在觀察的模型的深層副本。 另外,正如文檔所示:「爲了保存對象的值以供以後比較,使用了angular.copy函數,這也意味着觀看複雜選項會產生不利的內存和性能影響。」 因此,關注巨大的物體可能不是一個好主意。 – AlwaysALearner

+0

我被困在這幾次,所以我做了一個蹲下來證明不同之處:http://plnkr.co/edit/DHJPwMOg4LZTSk1uiV9z?p=preview – thebenedict