kittyminky
kittyminky

Reputation: 485

Angular Directive Call function from own scope

I am building an Angular directive which displays a list of items. The list of items is provided by a function from that directive's own scope. Below is a basic version of what I'm doing (listOpts needs to be a fn and isn't static data). When the template is compiled listOpts is not evaluated, so the template returns an empty ul. When I place the listOpts fn in the parent controller it evaluates it. But I do not want to put the listOpts function in the controller because of SRP (single responsibility principle); the listOpts function belongs to the list directive and not the controller. I must be misunderstanding something about how directives work or when the template is compiled? Should I be putting the listOpts fn in the controller fn with the directive?

@app.directive "list", () ->
  restrict: "E"
  link: (scope, el, attrs, ctrl) ->
    scope.listOpts = ()->
      return [1,2,3]

  template: "
    <ul ng-repeat='item in listOpts()'>
      <li>{{item}}</li>
    <ul>
  "

Upvotes: 0

Views: 91

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

The sample code provided seems to work as is:

http://plnkr.co/edit/r589eFGZm8MOTk94GJtk?p=preview

just modified to use regular JS, what's the issue here exactly, can you reproduce the problem in the plnkr.

.directive("list", function() {
  return {
  restrict: "E",
  link: function(scope, el, attrs, ctrl){ scope.listOpts = function(){return [1,2,3];}},
  template: "<ul ng-repeat='item in listOpts()'><li>{{item}}</li><ul>"
  }
})

Upvotes: 1

Related Questions