David Gustavsson David Gustavsson - 1 month ago 5
AngularJS Question

Angular: Correct way to send parameters to directive

I'm a bit new to Angular, and I am trying to get a grip on how to utilize Angular in a "correct" way regarding directives.

My use-case is that I'm developing a 3D-project viewer with Angular & ThreeJS. A user can have different "projects" that is available for him to view.

The way we want to utilize the project identification is through url parameters, so that a person is able to link a specific project to other people to view.

The Viewer/Renderer is defined as a directive, so that we can define the viewer as following

...
<viewer></viewer>
...


As I have understood it, there are some different ways to deliver the url parameters to the viewer-directive, and I'm trying to utilize $stateParams to access the parameter from the url. But as I continued working, there is no "clear" way to access the $stateParams, but you have to connect a controller to the directive, and then access it from there.

Is this the intended way to do this? Or should I define it as attributes to the viewer directive? If so, how do I access the url parameter in the html code? Or is there a third and better option?

As you probably understand I'm kinda new to angular, and I mainly want to get a grip of the intended usage of Angular, so that I don't screw up to much now at the start.

Best regards, David.

Answer

You can access your url parameters via scope, as you will be passing a string so @ makes more sense here :

scope: {
    datasource: '@'
}

In your directive you can pass the value like this:

<viewer datasource={{urlParamValue}}></viewer>

And in your controller, you can gather the url params like this:

function Controller($scope, $location){
    var urlParamValue = $location.search().urlParamValue;    
}
Comments