Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular.
I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a list of matches. The backend is straightforward and operational. On the frontend, I have implemented the search field and the results container:
<div id="search" ng-controller="FormController">
<input type="text" class="form-control input-lg" placeholder="Start typing . . ." ng-keypress="search()" ng-model="searchField" id="search-field">
<div id="results" class="alert alert-success">
<a href="#" ng-href="#" ng-repeat="item in items" ng-click="add(item)">
<p class="lead text-left">
<span>{{item.DisplayName}} -</span>
<span> {{item.Description}} -</span>
<span> {{item.Count}} ct. -</span>
<span> ${{item.Price}}</span>
<span class="glyphicon glyphicon-check pull-right"></span>
</p>
</a>
<h4>{{noResults}}</h4>
</div>
</div>
Two methods are called within my controller:
$scope.search = function()
{
$scope.$watch('searchField', function (newValue)
{
if (newValue)
{
$http.post('/search',
{
val: newValue
})
.success(function (response)
{
if (response.length > 0)
{
$scope.items = response;
$scope.noResults = '';
}
else
{
$scope.noResults = 'No Matches Found';
$scope.items = '';
}
})
.error(function (response)
{
console.log('Oooops, error: ' + response);
});
}
});
};
$scope.add = function(item)
{
console.log('added');
};
$scope.search()
is functional but add()
method does not trigger on click. It seems like I may not be within the scope of the controller at that point. Despite extensive research, I am stuck and seeking assistance. I have reached the frustrating "banging-your-head-against-the-keyboard-and-hopint-for-it-to-magically-work" phase.
Could this possibly be related to an inheritance issue?
** Update **
Here is the complete controller (with the $watch
removed as suggested in the comments):
var app = angular.module('AppModule', ['toastr']);
app.controller('FormController', ['$scope', '$http', 'toastr', function($scope, $http, toastr)
{
$scope.search = function()
{
var searchText = $scope.searchField;
$http.post('/search',
{
val: $scope.searchField
})
.success(function (response)
{
if (response.length > 0)
{
$scope.items = response;
$scope.noResults = '';
}
else
{
$scope.noResults = 'No Matches Found';
$scope.items = '';
}
})
.error(function (response)
{
console.log('Oooops, error: ' + response);
});
};
$scope.add = function(item)
{
console.log('added');
};
}]);
Update 2
Here is a plunker demonstrating that everything works up until the add()
method (which may have been renamed). Instead of my $http
post, I have hardcoded a simulated response from the server.