0

I am having hard time calling callback function inside ng-click under ng-repeat. Below is the snippet.

It is calling the ng-click function but when it is time to call the callback function - it fails - undefined - cb is not a function message

HTML part

<div ng-repeat="item in items">
  <span ng-click="itemClick(cb)">{{item}}</span>
</div>

Javascript

....
<script type="text/javascript">
  function cb(){
     alert('Hey');
  }
</script>

Angular

...
$scope.itemClick = function(cb) {
    cb();
};

I am new to angular.

4
  • 2
    wrong angular function, write this way $scope.itemClick = function(cb) {..........}, it may help Commented Dec 17, 2015 at 9:53
  • itemClick(item) is what you maybe want to achieve. Commented Dec 17, 2015 at 9:59
  • @JinnaBalu it is a typo error - i just type them, anyway it is in the correct format now, same with my code. Commented Dec 17, 2015 at 10:02
  • in itemClick function you are passing 'cb' as the variable, that is not used and you are trying to call cb() method. In Html on ng-click=ItemClick(cb), how you got cb variable. can you post you complete code Commented Dec 17, 2015 at 10:06

2 Answers 2

1

This is because when writing <span ng-click="itemClick(cb)">{{item}}</span> you expect cb to be a property on scope, but its not.

Its not very good practice to put functions global like this, like you're trying with cb. Why can't you just write whatever code you want to run ( alert('hey')) right inside $scope.itemClick-function?

Sign up to request clarification or add additional context in comments.

6 Comments

alert('hey') is just an example - in reality I am going to show reveal modal. I would like to open the modal on the html file where modal is defined.
so put that in the scope-function. Also like @Jinna Balu pointed out. Your scope function is not really valid javascript
as Gustav mentioned, you cannot access "not-angular-variables" in a parsed expression
@Mephiztopheles and Gustav got your point - but is it good idea to open up modal dialogs or other DOM related stuff inside controller function?
sure, there are services for this purpose. angular ui bootstrap for example has a $modal-service which you can use from your controller
|
0

angular will replace itemClick(cb)
with kinda
v1[...];var v0;if("cb" in s){v0 = s.cb} else if("cb" in l){v0 = l.cb} return v1(v0).

s is the scope and l is a object you can define when you want to pass variables into a function which you define in a directive: {click:"&"}
when you want to call the click-function, you do $scope.click({$event:event}) and this object will be passed as l.
so your global created cb is not available in your scope.

Greetings

Comments

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.