Ian
Ian

Reputation: 3676

Exiting a foreach within Angular Controller

Having just started with Angular I have struggled a little, now something as easy as a foreach loop seems pretty easy? If an element is found then return false and don't do anything below.

$scope.addFav = function($text, $link, $icon)
{

    var $favlist = $scope.favorites;

    $favlist.forEach(function(element, index, array) {
        console.log(element.name);
        console.log($text);
        if (element.name == $text)
        {
            console.log("Found");
            return false;
        }

    });

    $favlist.unshift({href: $link, name: $text, icon:$icon});

    if($favlist.length > 5)
        $favlist.pop();

    $scope.favorites = $favlist;

    return false;
};

My use case

<i class="fa fa-star-o" ng-click="addFav(item.name, item.href, item.icon);"

My question is where am I going wrong? The console is logged "Found" fine, but it doesn't stop the rest.

Upvotes: 1

Views: 72

Answers (1)

dfsq
dfsq

Reputation: 193301

By returning inside forEach callback won't prevent code outside from executing. In this case it's better to use Array.prototype.some method to check if array contains necessary value, and after that use simple if block to return or continue.

$scope.addFav = function ($text, $link, $icon) {

    var $favlist = $scope.favorites,
        found = $favlist.some(function (element, index, array) {
            return element.name == $text;
        });

    if (found) {
        return false;
    } 

    $favlist.unshift({
        href: $link,
        name: $text,
        icon: $icon
    });

    if ($favlist.length > 5) $favlist.pop();

    $scope.favorites = $favlist;

    return false;
};

Upvotes: 1

Related Questions