Paul Byrne
Paul Byrne

Reputation: 1615

Calling controller functions from the view in AngularJS

I have a function in my BlogController which changes the height of a div.

$scope.setTopBackgroundHeight = function (screenProportion, targetDiv) {
  globalService.setTopBackgroundHeight(screenProportion, targetDiv);
};

I am using this controller on a few pages, but only want to call this function on one page. So I put the call in my view as follows.

<div id="primary" 
     class="content-area blog-page" 
     ng-controller="blogCtrl">
     {{$scope.setTopBackgroundHeight("half", ".background-container");}}
</div>

Now, this works. But is calling a function from within curly braces in the view ok to do style wise? I've tried to find examples of doing something like this in the angular way, but can't see anything. Should it be in some ng directive?

Upvotes: 1

Views: 158

Answers (2)

jsSn0wMan
jsSn0wMan

Reputation: 3

This is what directives are for. Make sure to prefix them like angular does with "ng-click" but don't use ng.

Upvotes: 0

Wawy
Wawy

Reputation: 6269

Yes, all DOM manipulation should be done inside directives. So In this case it'd be better if you had a directive attached to the div that called that service method.

HTML:

<div id="primary" 
     class="content-area blog-page" 
     ng-controller="blogCtrl"
     setBGHeight>
</div>

JS:

app.directive('setBGHeight', function(globalService) {
  return {
    link: function() {
      globalService.setTopBackgroundHeight("half", ".background-container");
    }
  }
));

Upvotes: 1

Related Questions