0

I am quite familiar with CanJS, and kind of like the idea that you can instantiate a custom web widget on an HTML element, and now that we have an object, we can send messages to it (invoke a method on it):

lightbox.popUp();

or

reviewStars.setStars(3.5);

How could that be done in AngularJS? After you make a directive and set it on an HTML element or use the directive as an HTML element, how do you do something like above, as in OOP, or how Smalltalk would do it -- sending messages to a particular object?

I could think of a way, such as:

<review-stars api="ctrl.reviewStarAPI"></review-stars>

and then for the reviewStar directive, do this:

scope: { api: "=" }
link: function(scope, elem, attrs) {
    // first define some functions
    scope.setStars = function(n) { ... };

    // and then set it to the api object:
    scope.api.setStars = scope.setStars();
}

and then in the controller, do

vm.reviewStarAPI.setStars(3.5);

but this is a bit messy, and somewhat ad hoc. And it always need to have a controller... although, I suppose we can use 1 controller and as the main program and instantiate a bunch of objects and then invoke methods on them this way.

What is/are ways to accomplish this besides the method above?

Ashwin Balamohan
  • 3,303
  • 2
  • 25
  • 47
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • See a similar question already answered [here](http://stackoverflow.com/questions/16881478/how-to-call-a-method-defined-in-an-angularjs-directive). – Deepesh verma Mar 04 '16 at 05:07

1 Answers1

0

A modular approach to this would be to create a directive called reviewStars. The directive should have a parameter that indicates the star rating.

For example: <review-stars rating="3.5">

You would create using something like the following:

angular.module('myAngularModule', [])
.directive('reviewStars', function() {
  return {
    restrict: 'E',
    scope: {},
    bindToController: {
      rating: '@'
    },
    link: function(scope, elem, attrs) {
      // instantiate the lightbox code here
    },
    controller: function () {
      var vm = this;
      // controller code goes here (e.g. the onClick event handler)
    },
    controllerAs: 'ctrl',
    templateUrl: 'review-stars.html' // the HTML code goes in this file
  };
});

Check out Rangle's ng-course (https://github.com/rangle/ngcourse) or the Angular docs (docs.angularjs.org) for more on directives.

Ashwin Balamohan
  • 3,303
  • 2
  • 25
  • 47