0

Can i solve this problem, or it's a bad way with ng-repeat?

The markup:

<div ng-repeat="car in Ctrl.cars">
    <span>{{::car.color}}</span>
    <span>{{::car.type}}</span>
    <input ng-change="{{::car.function}}"/>
</div>

The js:

scope.cars = [
    {color: 'red', type: 'Ferrari', function:''},
    {color: 'green', type: 'Subaru', function: scope.doSomething},
];

I would like to run doSomething() on input change. You know a solution to this?

Thanks!

3 Answers 3

2

First, don't use function, since it's a JS keyword. Let's say you rename the field to functionToCall...

Second, you must not use interpolation, and you must call the function:

<input ng-change="car.functionToCall()"/>

If you want nothing to happen for some cars, then don't initialize the function to call with a string, initialize it with a function that does nothing:

{color: 'red', type: 'Ferrari', functionToCall: angular.noop}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it was useful, i am new in Angularjs, i didn't hear about angular.noop. Of course function is just example. :)
1

First thing I noticed regarding your snippet is that you are using a reserved keyword function as the key of a JS object. You are free to do so IF you let JS know it's a string: { "function": "someotherval" }

To call a function from the view, you could do this:

<input ng-change="car['function']()"/>

In case Angular cannot cope with this syntax, I'd suggest going with something like changeCallback as the key for the value. This worked for me:

<input ng-change="car.changeCallback()"/>
{color: 'red', type: 'Ferrari', changeCallback: scope.doSomethingAmazing }

The function itself need to be defined:

scope.doSomethingAmazing = function() { /* */ }

Comments

1

You're close yes... that's how it works you just do:

<input ng-model="car.myModel" ng-change="car.myFunction(car.myModel)"/>

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.