Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scope in @Directive #30

Closed
LalitAgrawala004 opened this issue Jun 29, 2017 · 4 comments
Closed

Scope in @Directive #30

LalitAgrawala004 opened this issue Jun 29, 2017 · 4 comments

Comments

@LalitAgrawala004
Copy link

Hi
I am trying to convert an existing directive using @directive decorator. This existing directive's controller method has $scope injected. When I am trying to inject $scope in decorator class's constructor I am getting provider error.. Any idea how to access $scope in @directive class..

@vsternbach
Copy link
Owner

Can you give me a more detailed example?

@LalitAgrawala004
Copy link
Author

I have something like

export default function testDirective($parse){
	'ngInject';

	return {
		restrict: 'AE',
		
		controller: function($scope, $attrs, TestService, $element){
			'ngInject';
			//logic here
		}
	};
}

in the controller function, we have $scope, $attrs $element injected.. I am converting it to @directive decorator class.. how would i achieve this?

I tried to do it as below -

@Directive({
	selector: '[test-directive]'
})
export class testDirective implements IDirective {
	public compile(elem: IAugmentedJQuery) {
	 	elem.css('display', 'none');
	}
	constructor(
		private $scope: any
		private $attrs:IAttributes,
		private $element: IAugmentedJQuery,
	) {
		'ngInject';
	}
}

but getting provider error in constructor.. So.. I removed the constructor and tried to implement link and controller functions as it is in IDirective interface.. but those are not getting executed only compile function is getting executed..

@vsternbach
Copy link
Owner

Since angular 2+ doesn't have analogs for compile or link functions you should move all of your code into controller, angular-ts-decorators has support for legacy link and compile as follows, if there's compile method defined on directive's class then it will be used, if there's no compile method, but link method, then it will be used(in both cases class itself isn't instantiated, i.e. injection in the constructor isn't executed), if both aren't defined, then the class itself will be used as directive's controller with the injection in it's constructor.

@vsternbach
Copy link
Owner

fixed in 2eef743

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants