Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 退出角度控制器内的foreach_Javascript_Angularjs - Fatal编程技术网

Javascript 退出角度控制器内的foreach

Javascript 退出角度控制器内的foreach,javascript,angularjs,Javascript,Angularjs,刚开始使用Angular时,我有点挣扎,现在像foreach循环这样简单的东西似乎很容易?如果找到一个元素,则返回false,并且不执行下面的任何操作 $scope.addFav = function($text, $link, $icon) { var $favlist = $scope.favorites; $favlist.forEach(function(element, index, array) { console.log(element.name

刚开始使用Angular时,我有点挣扎,现在像foreach循环这样简单的东西似乎很容易?如果找到一个元素,则返回false,并且不执行下面的任何操作

$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;
};
我的用例

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

通过返回内部
forEach
回调不会阻止外部代码执行。在这种情况下,最好使用方法检查数组是否包含必需的值,然后使用simple
if
block返回或继续

$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;
};

您想停止下面的forEach代码吗?非常感谢!我想如果我认为回报不会像我想要的那样起作用,但我不知道还有其他选择。如何处理角度文档?在这种情况下,它不是真正的角度文档,这是该语言的主要限制,您不能从循环中影响外部代码(只有当您抛出异常:)。