6

I'm new to AngularJS, and I've put an ng-click on a radio button generated by ng-repeat, and the click event refuses to fire. If I use a simple onclick, that does work though.

This works, and I see the alert:

<div class="span2 left-justify"
        ng-repeat="choice in physicalmode_choices">
    <input type="radio"
            name="physical_layer"
            value="{{ choice.private }}"
            onclick="alert('foo')"
            required
            ng-model="$parent.networkoptions.physicalmode" />
            &nbsp;<span ng-bind="choice.public"></span>
</div>

But this does not:

<div class="span2 left-justify"
        ng-repeat="choice in physicalmode_choices">
    <input type="radio"
            name="physical_layer"
            value="{{ choice.private }}"
            ng-click="alert('foo')"
            required
            ng-model="$parent.networkoptions.physicalmode" />
            &nbsp;<span ng-bind="choice.public"></span>
</div>

Can I not do this with an ng-click? Or am I misunderstanding what an "expression" is?

Thanks, Mike

1
  • Consider changing the title of this question, it doesn't describes the problem and its answer. Same problem would happen with any directive or structure, not only this one. Maybe something like ng-click doesn't recognise native javascript function Commented Aug 27, 2015 at 14:40

3 Answers 3

20

To clarify DerekR's answer.

When angular sees

ng-click='alert("test")'

it looks for

$scope.alert

which is likely to be undefined.

You need to provide a proxy method on the scope, or possibly even rootscope.

For example:

$rootScope.log = function(variable) {
    console.log(variable);
};
$rootScope.alert = function(text) {
    alert(text);
};

See: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED#scopemethods

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

Comments

2

When you call something inside of an ng-click the parsing service evaluates expressions against the scope rather than the global window object.

If you wanted to do an alert inside of an ng-click then could write a method on the scope or parent scope that in turn calls the alert.

Comments

1

I created this jsFiddle to show how it works.

http://jsfiddle.net/tM56a/1/

<li ng-repeat="menu in menus" >
     <a ng-click="test(menu)">click me</a>
</li>

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.