0

Say I've a simple array

$scope.array=[0,1,3,4,5,6];

and a view component where I want an ng-checked comparing with a vaule that must be in the array

`<ion-checkbox ng-checked="_.indexOf(array,1) !=-1"></ion-checkbox>`
`<ion-checkbox ng-checked="_.indexOf(array,2) !=-1"></ion-checkbox>`

I'm expecting the first checkbox being checked and not the second but they are both checked. Am I doing something wrong? thanks for help

5
  • 4
    Is there a variable named _ in your $scope? If not, _ is undefined. Why do you (try to) use underscore to do that in the first place? JS arrays have an indexOf method. Commented Aug 6, 2018 at 13:01
  • Yes I'm using underscore _ everywhere in app controllers.. I will try straight JS though Commented Aug 6, 2018 at 13:21
  • See AngularJS Developer Guide - AngularJS Expressions vs. JavaScript Expressions. Commented Aug 6, 2018 at 13:32
  • Show us the code of your controller, where you define the _ variable of the $scope then. Commented Aug 6, 2018 at 13:33
  • As you're probably using underscorejs or lodash, when you're using it from the methods in your javascript files it works. But once you're using inside the ng-checked it's looking for something like: $scope._.indexOf(...), if you want to keep using like this you can assign in your controller $scope._ = _;, but I prefer that you write a new method that receives your parameters and use the _ inside it. Commented Aug 6, 2018 at 13:38

2 Answers 2

2

AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings.

If you want to use Underscore, you should code a $scope function and call it:

Js:

$scope.exists = function(array, idx){
    return _.indexOf(array, idx) != -1;
}

HTML:

<ion-checkbox ng-checked="exists(array,1)"></ion-checkbox>

Alternatively, you might write

$scope._ = _;

From a Dependency Injection point of view you should provide Underscore as a constant.

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

Comments

1
<ion-checkbox ng-checked="array.indexOf(1)!=-1"></ion-checkbox>

You can try this one.

1 Comment

thanks to all, my question was over-simplified but you've cleared the concept. regading the usage of array.indexOf() or even _.indexOf() when comparing with the element with value 0 it always return false,. Said that I've worked around creating an object with string values, is there a safe way to match the 0 value with indexOf() ?

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.