2015-09-17 25 views
0

這裏是我的代碼如何讓JavaScript從HTML而不是硬編碼數據讀取?

HTML:

<div ng-app="myFirstApp" ng-controller="countriesController"> 

    <p> Search for a country: </p> 

    <p><input type="text" ng-model="test"></p> 

    <ul> 
     <li ng-repeat="x in countryList | filter:test"> 
     {{ x.country }} 
     </li> 
    </ul> 

</div> 

的javascript:

var app = angular.module('myFirstApp', []); 

app.controller('countriesController', function($scope) { 
    $scope.countryList = [ 
     {country:'Argentina'}, 
     {country:'Brazil'}, 
     {country:'Chile'}, 
     {country:'Colombia'}, 
     {country:'Paraguay'}, 
     {country:'Panama'}, 
     {country:'Andorra'} 
    ]; 


}); 

到目前爲止,我可以輸入到一個盒子裏,只返回匹配文本的國家。 我想做的事情。首先,如上所示,國家列表被硬編碼到JavaScript中。如果我有在HTML文件中像這樣一個標準的無序列表:

<ul id="countryList"> 
    <li>Argentina</li> 
    <li>Brazil</li> 
    <li>Chile</li> 
    <li>Colombia</li> 
    <li>Paraguay</li> 
    <li>Panama</li> 
    <li>Andorra</li> 
</ul> 

我怎樣才能拿到劇本使用這個數據,而不是它是硬編碼到JS。 另一個較小的查詢是如何讓js做不同的模式。例如,如果我現在輸入'a',所有返回'a'的國家。但我只希望在這種情況下返回以A開頭的國家。

感謝

+0

所以,你希望有一個「硬編碼」列表中的DOM(標記)和比JS讀出來?比爲什麼使用angularjs在第一個地方? - >你可以用jQuery或VanillaJS –

回答

0

基本上,如果你正在使用angularjs爲了這個目的,我會做不同的:

對於您的過濾器: 如果你想有一個100%的比賽,你可以只用「真」作爲您的過濾器第二個參數。

<ul> 
    <li ng-repeat="x in countryList | filter:test:true"> 
    {{ x.country }} 
    </li> 
</ul> 

否則,你必須寫一個過濾器功能(如文檔:https://docs.angularjs.org/api/ng/filter/filterAngularJs, filter case insensitive):

<ul> 
    <li ng-repeat="x in countryList | myFilter:test"> 
    {{ x.country }} 
    </li> 
</ul> 

app.filter("myFilter", function(){ 
    return function(items, test){ 
     var returnItems = items; 
     if(test === "") { 
     returnItems = items; 
     } 
    else { 
     returnItems = items.filter(function(element, index,array) { 
     if(element.country.indexOf(test) !== -1) 
     return true; 
     }); 
    } 
    return returnItems; 
    }; 
}); 

編輯:這裏是一個jsbin(工作):https://jsbin.com/ruheditude/6/edit?html,js,output

我錯了要使用$ scope,您必須使用$ app。更新的代碼示例

+0

來做到這一點,這個答案很棒,在我標記之前還有一件事。我在哪裏怪怪$ scope.myFilter的事情。我把它放在我的js代碼中,但到目前爲止它沒有被拾取 –

+0

更新了一些(因爲它之前是一種原型),這裏是jsbin https://jsbin.com/ruheditude/6/edit?html ,JS,輸出 –

0

首先,數據必須在某處定義。至少在數據庫中,或者您可以生成這些數據。無論哪種方式,只要您獲得應用程序外部的數據,對您而言,它就是動態的。

所以你可以創建.json文件並以同樣的方式抓取,我已經調用URL來獲取數據。我移動數據檢索的原因是,您可以在應用程序的其他位置重新使用代碼。開發角度應用程序時,這是一個很好的做法。

爲了實現您的「開始」行爲 - 我實施了一個過濾器,下面將對此進行說明。

我已經實現了一個完整的例子。因爲這對我來說也是很好的學習。以下是我創建的那個過濾器的用法。

<ul> 
    <li ng-repeat="user in users | startsWith:searchText | orderBy: 'name' "> 
     {{user.name}} | {{user.company.name}} 
    </li> 
</ul> 

JSFiddle: StartWith

相關問題