23

I have made a function getAge() in my custom.js. This function needs to be called in my HTML page.

So what i tried is like this :-

<td>{{getAge(user.basicinformation[0].dateofbirth)}}</td>

I can see no results.

How to call function in HTML?

1
  • so u need to create filter for this Commented May 22, 2014 at 5:32

2 Answers 2

40

So create a filter for getAge.

app.filter("getAge", function(){
   return function(input){
      // Your logic
      return output; 
   }
});

Then call it in HTML:

<td>{{ user.basicinformation[0].dateofbirth | getAge }}</td>
Sign up to request clarification or add additional context in comments.

2 Comments

But @NitishKumar , $scope.user = user is the way to do it in Angular. You would need to do it in your solution, anyway or else the filter couldn't access the user object.
I think 'filter' (for ng $filter) was a really poor choice of name for this, given that filter is also used in Angular (and in native JavaScript) when selecting a subset of items from an array. So, $filter and filter are two completely different things in Angular. The former should have been called formatter or transformer perhaps.
25

Attach getAge and user to the $scope of the pages controller.

$scope.user = user;
$scope.getAge = getAge;

Make sure you're doing this in the controller and setting up the controller correctly. It won't work unless you've set up a controller with this DOM view and injected the $scope service into the controller.

3 Comments

It do works when i have this function with $scope in controller... As this function is used in many places, i have shifted this function in custom.js file. Doesn't work when function is in custom.js file
I would just create a reference to getAge and user within the scope, as in my answer. It can still be in the custom.js file. That's the only way you'll be able to access them in your {{ brackets }}
$scope.getAge = function(){ /** function body */ } . And inside your html page call {{getAge()}}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.