<...">

Link directive attribute with vm, not $ scope

I have a custom directive that looks like this:

<my-queue id="report.id" version="report.version"></my-queue> 

In my directive definition object, I refer to my controller and scope as follows:

 controller: 'QueueController', controllerAs: 'myQueue', scope: { id: '=', version: '=' } 

In my controller, I set var vm = this , so I can refer to sphere variables as vm.variable . However, this does not work for id and version . I found that I need to enter $scope and refer to these properties as $scope.id and $scope.version . Is there a way to set this so that I can not enter $scope and stay consistent with the rest of my controller, referencing vm.id and vm.version ?

+5
source share
1 answer

The controllerAs property in your directive configuration object will be used by you to reference the instance of your controller, so if you want to use vm in your template, you need to set the controllerAs property to vm . In addition, by setting the bindToController property to true , you can bind directly to the view model instead of $ scope:

 function myQueue() { return { restrict: 'E', template: ... , controller: myQueueCtrl, controllerAs: 'vm', scope: { id: '=', version: '=' }, bindToController: true } } 

With your current directive configuration, your controllerAs link will be under myQueue , not vm , i.e. any properties you created on vm (e.g. vm.id ) in your controller will be on myQueue in your template (e.g. myQueue.id ) .

By adding bindToController , we do not need to enter $ scope in the directive controller:

 function QueueController() { var vm = this; } 

You can then reference your var in the directive template as

 {{vm.id}} {{vm.version}} 

There is your directive here with bindToController set to true and controllerAs to vm .

+4
source

All Articles