2015-09-11 68 views
3

我使用pretty nice plugin,它为AngularJS提供标签输入指令。角度标签指令问题

我使用参数onTagAdding在将标签添加到输入之前检查标签的值。

on-tag-adding="{expression}" 

所以,作为文档说:来评估,这将增加一个新的标签之前调用

表达。 新标签可作为$标签使用。此方法必须返回true或false。如果为false,则不会添加标签。

所以这里是一个live example

$scope.checkTag = function(tag) { 
    angular.forEach($scope.forbiddenTags, function(e){ 
     if (e.text === tag.text) { 
      alert('Tag is forbidden') 
      return false; 
     } 
    }) 

    alert('Execution is continuing'); 
} 

我期待,如果输入的值匹配一个从$scope.forbiddenTags阵列,然后这些标签应返回和功能的执行应停止,但它的工作原理并不像我期待=)。我已经尝试返回,但它也不起作用。

任何帮助和建议,将不胜感激!提前致谢!

回答

3

问题是,从forEach迭代器函数返回没有用,它不会像预期的那样最终从外部checkTag函数返回该返回值。你可以尝试这样的事情。

$scope.checkTag = function(tag) { 
var found = $scope.forbiddenTags.some(function(ftag){ 
    if (ftag.text === tag.text) { 
     alert('Tag is forbidden'); 
     return true; 
    } 
    //If you do not need alert then just do 
    // return (ftag.text === tag.text); 
}); 
return !found; 
} 

我使用array.some(检查出的垫片,如果需要支持IE < 9)在这里,让我通过,一旦找到匹配循环的退出了(以避免不必要的重复,你不能用forEach办)同时返回布尔值。您也可以使用传统的for循环作为使用返回。如果你想继续使用forEach,那么保存一个布尔型标志,找到并返回它。

$scope.checkTag = function(tag) { 
    var found = false; 
    angular.forEach($scope.forbiddenTags, function(e){ 
     if (e.text === tag.text) { 
      alert('Tag is forbidden') 
      found = true; 
      //A return here is of no use as it will not break out of the loop 
     } 
    }); 

    alert('Execution is continuing'); 
    return !found; //If found is true then return false and vice versa 
} 
+0

很酷!它就像一个魅力=)感谢您的答案和很好的解释! – user3673623

+1

@ user3673623不客气。 :)注意: - 你也可以使用[Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find),[Array.findIndex]( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)与Shim支持,但'array.some'会更精确。 – PSL

+1

@PSL关于IE> 9的支持:) –