2

如何正確使用隔離範圍屬性?如何正確使用隔離範圍屬性?

我有一個指令,它是從一個頁面控制器調用的,其屬性item傳遞給它,例如, <my-directive item="myItem"></my-directive>,包含id

下面的代碼將不起作用,因爲它似乎$scope.item未被定義在控制器中..就像我太快使用它。我如何確定在我想要使用它時實際設置了它?

app.directive('myDirective', [function() { 
return { 
    restrict: 'E', 
    templateUrl: 'template.html', 
    scope: { 
     item: "=" 
    }, 
    controller: ['$scope', 'ExtendedItemFactory', function($scope, ExtendedItemFactory) { 
     this.extendedInfo = ExtendedItemFactory.get({ id: $scope.item.id }); 
    }], 
    controllerAs: 'MyDirectiveCtrl' 
}; 
}]); 

回答

1

你可以使用你的$watch指令,將在改變觀賞價值&會火,你想裏面的代碼。

代碼

app.directive('myDirective', [function() { 
    return { 
     restrict: 'E', 
     templateUrl: 'template.html', 
     scope: { 
      item: "=" 
     }, 
     controller: ['$scope', 'ExtendedItemFactory', function($scope, ExtendedItemFactory) { 
      this.extendedInfo = ExtendedItemFactory.get({ 
       id: $scope.item.id 
      }); 
      $scope.$watch('item', function(newVal, oldVal) { 
       if (newVal && newVal != oldVal) 
        this.extendedInfo = ExtendedItemFactory.get({ 
         id: $scope.item.id 
        }); 
      }, true).bind(this); 
     }], 
     controllerAs: 'MyDirectiveCtrl' 
    }; 
}]); 
+1

使用'$ watch'確實工作! – Andreas

+1

我不得不說,角度不提供更簡單的本地解決方案是很奇怪的。 – Andreas

+0

@Andreas是的,它會在沒有'.bind(this)'的情況下工作,因爲我們正在直接訪問isolatated scope變量..如果我們想使用鏈接的範圍變量到指令控制器,那麼只有我們會使用'.bind(this) '..如果它確實幫助了你,那就投票贊成..那麼.. –

0

您使用controllerAs,所以你不需要在這種情況下注入$範圍。

我想你的指令定義更改爲以下,注意使用bindToController,這將確保您的隔離範圍值,填充和可用的控制器上:

app.directive('myDirective', [function() { 
    return { 
     restrict: 'E', 
     templateUrl: 'template.html', 
     scope: { 
      item: "=" 
     }, 
     controller: ['ExtendedItemFactory', function(ExtendedItemFactory) { 
      this.extendedInfo = ExtendedItemFactory.get({ id: this.item.id }); 
     }], 
     controllerAs: 'MyDirectiveCtrl', 
     bindToController: true 
    }; 
}]); 
+0

這似乎不起作用,在試用你的代碼時,'item'尚未在控制器中定義。 – Andreas

+0

你能告訴你如何使用該指令嗎? – natwallbank

+0

''其中'myItem'是頁面控制器上的作用域變量。 – Andreas

0

相反初始化extendedInfo當指令加載你可以創建getter函數,根據需要檢索它。

this.getExtendedInfo = function(){ 
    return ExtendedItemFactory.get({ id: $scope.item.id }); 
} 

或者阻止您的指令加載,直到item準備

<div ng-if="ctrl.item"> 
    <my-directive item="ctrl.item"></my-directive> 
</div> 
+0

我必須直接在加載時加載信息,所以你的第一個建議不起作用。你的第二個建議是一個有趣的方法,但將邏輯置於指令本身之外感覺不對...... – Andreas

相關問題