Reputation: 155
So I have the code for a search bar in its own template, which I have in a custom directive. Then I put that directive in the my Navbar template.
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" ng-model="searchText">
</div>
<button type="submit" class="btn btn-default" ng-click="go('/searchResults')">Submit</button>
</form>
.
.state('searchResults', {
url: '/searchResults',
templateUrl: 'templates/searchResults.html',
controller: 'searchController'
})
}]).
directive('searchBar', function() {
return {
restrict: 'E',
templateUrl: 'templates/search.html',
controller: "searchController"
}
});
My SearchController handles the scope for this search bar, but I'm having some trouble binding data to another template, which is my searchResults template. My SearchController calls on a service I wrote which retrieves some data and works fine. When I try to bind the data to my SearchResults page however, angular does not bind any of the data received from the service, (it will console log out the correct data though).
Name: {{player.playerName}}<br>
Link: {{player.link}}<br>
Things: {{things}}<br>
controller:
angular
.module('app')
.controller('searchController', ['$scope',"$http","$location", "PlayerDAO", function($scope, $http, $location, PlayerDAO){
$scope.things="stuff";
$scope.go = function ( path ) {
if(checkSearchBar()){
$location.path( path );
PlayerDAO.getPlayers($scope.searchText).then($scope.postPlayerToResultsPage, onError);
}
};
$scope.postPlayerToResultsPage=function(result){
$scope.player=result;
$scope.things="Hooray, it worked";
$scope.player.playerName;
console.log(result);
};
}]);
Oddly enough to me however, it will bind any data that is not in the function I use to get the data (i.e. it will bind {{things}}), but any of the data in my function "postPlayerToResultsPage", isn't seen by Angular. If I take the code for the search bar and put it in my search results page directly, the nav-bar that appears on that page works flawlessly, however I need the search-bar to be on my main navigation template, view-able on all pages.
Upvotes: 3
Views: 516
Reputation: 3651
I suspect your data isn't binding due to the prototypical nature of your directive's $scope. Try using controllerAs syntax for data binding to avoid $scope ambiguity. e.g.
directive:
controller: 'searchController',
controllerAs: 'searchCtl'
controller:
var controller = this;
$scope.postPlayerToResultsPage=function(result){
controller.player=result;
controller.things="Hooray, it worked";
controller.player.playerName;
console.log(result);
};
html:
Name: {{searchCtl.player.playerName}}<br>
Link: {{searchCtl.player.link}}<br>
Things: {{searchCtl.things}}<br>
Upvotes: 1