AngularJS directive, ControllerAs, scope and vm property

我们两清 提交于 2019-12-13 01:23:10

问题


Using Angular I created a directive like this:

angular
    .module('my-module', [])
    .directive('myDirective', function () {

        return {
            restrict: 'E',
            templateUrl: currentScriptPath.replace('.js', '.html'),
            scope: {
                scenarios: '='
            },
            controller: MyDirectiveController,
            controllerAs: 'vm',
            bindToController: true,
            replace: true
        }

    });

MyDirectiveController:

MyDirectiveController.$inject = ['$scope'];

function MyDirectiveController($scope) {
    var vm = this;
    vm.scenarios = $scope.scenarios;
}

My directive HTML template is this:

<div>{{vm.scenarios[0].name}}</div>

In my parent view HTML I'm using the directive this way:

<my-directive scenarios="vm.scenarios"></my-directive>

The parent controller has a property:

vm.scenarios = [] // could be [{ name : "test"}]

As the vm.scenarios of the parent controller gets set after an $http call it is not available when the vm.scenarios of the directive controller is bound to the $scope.scenarios and it doesn't get updated when the parents controller vm.scenarios gets populated eventually.

When adding this to my directives controller, it works but the solution seems wrong to me:

$scope.$watch('scenarios', function(newValue) {
    if (newValue !== undefined) {
            vm.scenarios = $scope.scenarios;
    }
});

回答1:


This is how you should define your directive controller:

MyDirectiveController.$inject = [];

function MyDirectiveController() {
    // nothing here
}

You don't need to use $scope because you already bind to controller instance this. It means that scope config

scope: {
    scenarios: '='
},

populates controller instance this object, not $scope object, and hence $scope.scenarios is undefined. With vm.scenarios = $scope.scenarios; in controller you just overwrite correct binding with undefined value.

Demo: http://plnkr.co/edit/lYg15Xpb3CsbQGIb37ya?p=preview



来源:https://stackoverflow.com/questions/31357698/angularjs-directive-controlleras-scope-and-vm-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!