我正在尝试在我的网页上实现基本的最近搜索列表。单击搜索按钮时,会将两个输入连接起来并推送到名为“recentSearchItems”的数组中。 recentSearchItems以空数组开头,即使在homeCtrl上更新,也永远不会在指令上更新。
index.html:
<body ng-controller="HomeCtrl">
<div class="outer-wrapper">
<div class="main-wrapper" ng-class="{'search-page': searchClicked}" ng-show="uiRouterState.current.name == 'home'">
<div class="home-logo" ng-class="{'animate': searchClicked}">
</div>
<div class="home-content-wrapper" ng-class="{'animate': searchClicked}">
<div class="main-header" ng-class="{'animate': searchClicked}">
Lorem ipsum dolor sit!
</div>
<div class="main-large-text" ng-class="{'animate': searchClicked}">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<form class="form-elements">
<input type="text" class="large-textbox" name="looking-for" placeholder="I am looking for" ng-model="placeKeyword">
<input type="text" class="medium-textbox" name="place" placeholder="Istanbul" ng-model="placeNear" style="margin-left: 10px;">
<button ui-sref="home" class="search-btn" style="margin-left: 10px;" ng-click="startSearch()">
<span></span>
</button>
</form>
</div>
</div>
<div ui-view></div>
<div class="footer-wrapper">
<div class="footer-links">
<a href="#">About us</a>
<a href="#">Contact</a>
<a href="#">Blog</a>
</div>
</div>
</div>
</body>
内容的html(替换上面的“ui-view”指令):
<div class="search-items" ng-show="uiRouterState.current.name == 'home'">
<div class="places-list">
<place-grid ng-repeat="place in places"></place-grid>
</div>
<recent-searches recent-search-items="recentSearchItems"></recent-searches>
</div>
homeCtrl:
placesApp.controller("HomeCtrl", ["$scope", "$state", "FoursquareApiService", ($scope, $state, FoursquareApiService) => {
$scope.uiRouterState = $state;
$scope.searchClicked = false;
$scope.recentSearchItems = [];
$scope.startSearch = () => {
if($scope.placeNear) {
$scope.addToSearchHistory($scope.placeKeyword, $scope.placeNear);
$scope.searchClicked = true;
var promise = FoursquareApiService.getPlaces($scope.placeNear, $scope.placeKeyword);
promise.then(
function(response) {
$scope.places = response;
},
function(error) {
console.log("Couldn't get the places data: " + error)
}
);
}
};
$scope.addToSearchHistory = (placeKeyword , placeNear) => {
$scope.recentSearchItems.push(placeKeyword + " in " + placeNear);
};
}]);
指令:
placesApp.directive("recentSearches", () => {
return {
restrict: "E",
replace: true,
scope: {
recentSearchItems: "="
},
templateUrl: "views/recent-searches.html"
}
});
指令模板:
<div class="recent-searches">
<h3>RECENT SEARCHES</h3>
<hr class="under-header">
<div class="recent-search-items" ng-repeat="recentSearchItem in recentSearchItems">
<p ng-bind="recentSearchItem"></p>
<hr>
</div>
</div>
答案 0 :(得分:0)
将bindToController: true
添加到指令
placesApp.directive("recentSearches", () => {
return {
restrict: "E",
replace: true,
scope: {
recentSearchItems: "="
},
templateUrl: "views/recent-searches.html",
bindToController: true
}
});