简体   繁体   English

无法在指令的控制器中访问指令的作用域对象

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

MaterialIn.directive.js 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

}

Hi everyone.i made a directive and send it an array of objects "materialoffers",i can access it on the html page it is working fine,but idk why i cant access it inside the controller,it shows undefined,can anyone please tell me a way i can use that materialoffers inside the controller,i want to get its length and store it in a $scope variable like this 嗨,大家好。我做了一个指令,并向它发送了一系列对象“ materialoffers”,我可以在html页面上访问它,它工作正常,但是idk为什么我不能在控制器内访问它,它显示未定义,任何人都可以告诉我以一种方式可以在控制器内使用该材质,我想获取其长度并将其存储在这样的$ scope变量中

vm.total=vm.materialoffers.length;

Seems like materialoffers variable may get its value after a $http call or similar, as in it doesn't instantly have a value when the directive is created. 似乎materialoffers变量可能在$ http调用或类似调用后获得其值,因为在创建指令时它不会立即具有值。 The console.log(vm) shows the variable since it shows the state of the object (vm in this case) when you click it. console.log(vm)显示变量,因为单击时它显示对象的状态(在本例中为vm)。 You can test this phenomenon with the following code in your browser console: 您可以在浏览器控制台中使用以下代码测试这种现象:

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

If you click the object before the 10 seconds have passed, it won't have the property, but after you click on it after 10 seconds, you will see the added property there. 如果在10秒钟过去之前单击该对象,它将没有该属性,但是在10秒钟之后单击该对象之后,您将在此处看到添加的属性。

Try replacing your controller code with this: 尝试以此替换您的控制器代码:

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