簡體   English   中英

無法在指令的控制器中訪問指令的作用域對象

[英]cannot access directive's scope object in directive's controller

MaterialIn.directive.js

angular.module('mdt')
    .directive('mdtMaterialins', materialInsDirective);

function materialInsDirective() {
    return {
        restrict: 'E',
        scope: {
            materialoffers: '=',

        },
        bindToController: true,
        templateUrl: 'app/materialOffers/materialIns/materialIns.html',
        controllerAs: 'materialInsVm',
        controller: MaterialinsController
    };
}
function MaterialinsController($scope) {
    var vm = this;
console.log(vm);  //shows the materialoffers object present
console.log(vm.materialoffers);  //show undefined

}

嗨,大家好。我做了一個指令,並向它發送了一系列對象“ materialoffers”,我可以在html頁面上訪問它,它工作正常,但是idk為什么我不能在控制器內訪問它,它顯示未定義,任何人都可以告訴我以一種方式可以在控制器內使用該材質,我想獲取其長度並將其存儲在這樣的$ scope變量中

vm.total=vm.materialoffers.length;

似乎materialoffers變量可能在$ http調用或類似調用后獲得其值,因為在創建指令時它不會立即具有值。 console.log(vm)顯示變量,因為單擊時它顯示對象的狀態(在本例中為vm)。 您可以在瀏覽器控制台中使用以下代碼測試這種現象:

var object = {};
object; // logs the object in console, shows an empty object
window.setTimeout(function() {
    object.testValue = "test value"
}, 10000) // After 10 seconds, the object will get the property testValue

如果在10秒鍾過去之前單擊該對象,它將沒有該屬性,但是在10秒鍾之后單擊該對象之后,您將在此處看到添加的屬性。

嘗試以此替換您的控制器代碼:

function MaterialinsController($scope) {
    var vm = this;

    $scope.$watch(function() { return vm.materialoffers }, function() {
        console.log(vm.materialoffers)
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM