angularjs:vm是未定义的,当在指令中使用contronllerAs语法时

时间:2016-03-17 13:41:44

标签: javascript angularjs angularjs-directive

我无法从相关控制器访问vm.screensize属性。我收到的错误是没有定义vm。以下是指令和控制器。

    angular.module('app.ain.directives')
.directive('ainProjectWizardExplanations', function() {
    return {
        restrict: 'E',
        bindToController: true,
        scope : {
            sidenavHidden : '='
        },
        controller: 'ProjectWizardExplanationsController as vm',
        templateUrl: function() {
          console.log(vm.screensize, vm.animate);
            if(vm.screensize) {
                return 'app/ain/shared/directives/projectWizardExplanationsMobile.html';
            }else {
                return 'app/ain/shared/directives/projectWizardExplanations.html';
            }
        }
    };
});


    //controller
angular
        .module('app.ain.directives')
        .controller('ProjectWizardExplanationsController', ProjectWizardExplanationsController);

    function ProjectWizardExplanationsController($mdMedia,$scope,$rootScope, $timeout) {
                var vm = this;
                vm.animate = true;
                $scope.$watch(function() { return $mdMedia('sm'); }, function(small) {
                    vm.screensize = small;
                });
        }

1 个答案:

答案 0 :(得分:0)

尝试设置" controllerAs"改为声明指令时的选项。

.directive('ainProjectWizardExplanations', function() {
return {
    restrict: 'E',
    bindToController: true,
    scope : {
        sidenavHidden : '='
    },
    controller: 'ProjectWizardExplanationsController',
    controllerAs: 'vm',
    templateUrl: function() {
      console.log(vm.screensize, vm.animate);
        if(vm.screensize) {
            return 'app/ain/shared/directives/projectWizardExplanationsMobile.html';
        }else {
            return 'app/ain/shared/directives/projectWizardExplanations.html';
        }
    }
};
});

希望对你有用:)