Skip to content Skip to sidebar Skip to footer

Angularjs: Accessing An Element Directive's Attributes From Within A Controller

Problem: The attribute I pass to my directive's controller is not evaluated. For example, I get {{ attribute.value }} instead of 5. Desired Outcome: My directive's controller has a

Solution 1:

You can actually create a custom directive like this:

functionbookingWidget() {
        return {
            restrict: 'E',
            scope: {
                boatId: '@'
            },
            templateUrl: "/static/app/trips/trips.bookingwidget.template.html",
            controller: 'BookingWidgetController as bookingCtrl',
            link : function(scope, element, attrs, controller){
               console.log(attrs.boatId);
               scope.boatId = attrs.boatId;
            }
        }
    }

The link function actually allows you to have an access to the element, the scope of the directive, the attributes associated to the directive and the controller of the directive. The function is called after everything associated to the directive has been performed. In other words, this is the last stage.

The same scope would be shareable between the link function and controller.

Now, to make the API call, you may actually add a function in your controller that accepts the boatID, makes a call to the API and accepts the response onto the controller object. After that, add a watcher within the link function that watches over "vm.boatId", within which you may call that function which makes the API call. So, even if the controller has initialized before the link function, you would still be able to perform what you wish to. So, it would be a "link-based activation".

You may give this solution a try. Hope it helps.

Solution 2:

You can pass a function and call it. Need to use & then.

https://thinkster.io/egghead/isolate-scope-am

Post a Comment for "Angularjs: Accessing An Element Directive's Attributes From Within A Controller"