Lendro
Lendro

Reputation: 1

How do I execute functions in expressions?

I am pretty new to Angularjs, and I was trying to execute a function with a expression in HTML, but it didn't work. What do I need to change in my expression?

I tried replacing {{fullName}} with {{fullName()}, but then nothing was in the HTML display.

`

<div ng-app="appNaming" ng-controller="ctrlNaming">
    <p>Hey guys! My name is {{fullName}}.</p>
  </div>
  <script>
    var naming = angular.module('appNaming', []);
    naming.controller('ctrlNaming', function ($scope) {
      $scope.firstName = "Bob";
      $scope.lastName = "Ross";
      $scope.fullName = function () {
        return $scope.firstName + " " + $scope.lastName;
      }
    });
  </script>

`

I expected for the HTML to display Bob Ross as the full name, but instead the output was the function, aka `

function () { 
    return $scope.firstName + " " + $scope.lastName; 
}

`

Upvotes: 0

Views: 68

Answers (3)

vrdrv
vrdrv

Reputation: 313

You should avoid using $scope in component's controller. It makes migration to newer angular versions difficult. Instead use controller's this as context.

Try this:

<div ng-app="appNaming" ng-controller="ctrlNaming as $ctrl">
    <p>Hey guys! My name is {{$ctrl.fullName()}}.</p>
  </div>
  <script>
    var naming = angular.module('appNaming', []);
    naming.controller('ctrlNaming', function () {
      var $ctrl = this;

      $ctrl.firstName = "Bob";
      $ctrl.lastName = "Ross";
      $ctrl.fullName = function () {
        return $ctrl.firstName + " " + $ctrl.lastName;
      }
    });
  </script>

Upvotes: 0

astonTY
astonTY

Reputation: 59

Try like this:

$scope.fullName = (function () {
    return $scope.firstName + " " + $scope.lastName;
  })()

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22213

You can directly add 2 strings, no need to use a function.

Try like this:

$scope.fullName = $scope.firstName + " " + $scope.lastName;

Upvotes: 2

Related Questions