首頁  >  問答  >  主體

angular.js - ng-if 定義一個方法,回傳字串,為什麼不對

這樣寫是對的

<li ng-repeat="(x, y) in item" ng-if="x!='a'"></li>

這樣寫就是輸出全部的,ng-if並沒有執行

<li ng-repeat="(x, y) in item" ng-if="test()"></li>

...

$scope.test = function(){
    return "x!='a'"
}
PHP中文网PHP中文网2714 天前510

全部回覆(2)我來回復

  • 漂亮男人

    漂亮男人2017-05-15 17:06:14

    第一你沒有把x傳進去,第二你回傳的是一個字串,字串永遠是對的。這樣寫再試試看:

    <li ng-repeat="(x, y) in item" ng-if="test(x)"></li>
    
    $scope.test = function(x){
        return x!='a';
    }

    回覆
    0
  • 为情所困

    为情所困2017-05-15 17:06:14

    告訴你一個概念, ng-if中的東西叫做angular表達式,angular會對這個表達式進行parse。
    "x!='a'"其實就是$scope.x != 'a',順帶一提這個$scope是< code>ng-repeat產生的scope。 "x!='a'"其实就是$scope.x != 'a',顺带一提这个$scopeng-repeat产生的scope。
    下面的test()当然会变parse成$scope.test()在ngRepeat的scope中没找到方法,所以从父scope中找到了你的方法, 然后你的方法return的是一个字符串, 所以判断永远是true下面的test()當然會變parse成$scope.test()在ngRepeat的scope中沒找到方法,所以從父scope中找到了你的方法, 然後你的方法return的是一個字串, 所以判斷永遠是true了。

    回覆
    0
  • 取消回覆