2

我想在我的html文件中調用ng-init中的函數。 該函數進行API調用並提供數據。我將該數據分配給作用域變量並將該作用域變量傳遞給指令。Angularjs - 在ng-init函數完成後調用指令

控制器首先擊中。但是在APIi調用完成指令之前就已經完成了。所以我傳遞給控制器​​的範圍變量是未定義的。

App.directive('foldertree', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      'inputfromapicall': '=', 
      'fileName': "=" 
     }, 
     link: function (scope, element, attrs, ngModelCtrl) { 

      return $timeout(function() {    
       $('#divid').fileTree({ 
        root: scope.inputfromapicall, //undefined 
        script: '/project/current/source/data/jqueryFileTree.jsp', 
        expandSpeed: 1, 
        collapseSpeed: 1, 
        multiFolder: false 
       }, function (file) { 
        scope.fileName = file;     
        scope.$apply(); 
       }); 
      }); 
     } 
    }; 
}); 

以上就是我的指令代碼

對不起張貼模糊question.Hope有人幫我修復。

+1

你應該看$在該指令模式的轉變。 ng-init也不適合做api調用。最好從控制器進行此調用。 – 2014-10-30 16:07:24

回答

2

正如MajoB在評論範圍中提到的那樣,$ watch取得了訣竅。這是我更新的指令代碼。

automateOnApp.directive('foldertree', ['$timeout', function($timeout){ 
    return { 
     restrict: 'A', 
     scope: { 
      'inputfromapicall': '=', 
      'fileName': "=" 
     }, 
     link: function (scope, element, attrs, ngModelCtrl, controller) { 
      scope.fileName = ''; 
      return $timeout(function() { 


       scope.$watch(function() {       
         return scope.inputfromapicall; 
       }, function(newVal) {      

         if(!angular.isUndefined(scope.inputfromapicall)){ 
          $('#divid').html(''); 
          $('#divid').fileTree({ 
            root: newVal, 
            script: '/project/current/source/data/jqueryFileTree.jsp', 
            expandSpeed: 1, 
            collapseSpeed: 1, 
            multiFolder: false 
          }, function (file) {       
            scope.fileName = file;     
            scope.$apply(); 
          }); 
         } 
       }); 

      }); 
     } 
    }; 
}]); 

希望它可以幫助別人在未來