我正在学习AngularJS,我终于有了一些工作(我实现了搜索功能)
现在,我正在尝试根据AngularJS中的搜索代码构建一个菜单。
一切正常但我必须一遍又一遍地重复相同的代码:
ng-model="searchText" ng-click="search('link-6')"
这是我的代码:
<!DOCTYPE html>
<html ng-app="casz">
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<section ng-controller="SearchCtrl">
<nav>
<a href="/link-1/" ng-model="searchText" ng-click="search('link-1')" >link-1</a>
<a href="/test/" ng-model="searchText" ng-click="search('test')" >test</a>
<a href="/link/" ng-model="searchText" ng-click="search('link')" >link</a>
<a href="/link-4/" ng-model="searchText" ng-click="search('link-4')" >link-4</a>
<a href="/stackoverflow/" ng-model="searchText" ng-click="search('stackoverflow')" >stackoverflow</a>
<a href="/link-6/" ng-model="searchText" ng-click="search('link-6')" >link-6</a>
<a href="/link-abc/" ng-model="searchText" ng-click="search('link-abc')" >link-abc</a>
<a href="/link-8/" ng-model="searchText" ng-click="search('link-8')" >link-8</a>
<a href="/zzz/" ng-model="searchText" ng-click="search('zzz-9')" >zzz</a>
</nav>
<article ng-repeat="d in data">
<h3>{{d.title}}</h3>
<p>{{d.description}}</p>
</article>
</section>
<!-- JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('casz',[]);
app.controller("SearchCtrl", function($scope, $http) {
$scope.search = function(p) {
$http({
cache: false,
dataType: 'json',
url: '/getdata.php?',
method: "POST",
data: 'title=' + p,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.status = status;
$scope.data = data;
}).error(function (data, status, headers, config) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
});
</script>
</body>
</html>
有没有办法不重复这段代码&#34; ng-model =&#34; searchText&#34;纳克单击=&#34;搜索(&#39;链接-6&#39;)&#34;并使用数据或类似的东西?
===我编辑了我的问题===
答案 0 :(得分:2)
您可以创建一系列链接,并通过ng-repeat
<a ng-repeat="link in links"
ng-href="/link-{{link}}/"
ng-model="searchText"
ng-click="search('link-' + link)" >
link-{{link}}</a>
<强> Example Plnkr 强>