I have an simple app with a input box where if a user types something in the input box an alert message is triggered every-time the user types something (using a keyup).
I want to use a directive for the input box (called searchBar) and call a controller function every time something is inputted.
var app = angular.module('HelloApp', [])
app.directive('searchBar', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="search" placeholder="Enter a search" />',
link: function(scope, elem, attrs) {
elem.bind('keyup', function() {
elem.css('background-color', 'white');
scope.$apply(function() {
scope.search(elem);
});
});
}
};
});
app.controller('searchbarcontroller', ['$scope', function($scope) {
$scope.search = function(element) {
alert ("keypressed. Value so far is: " + element.target.val());
};
}]);
Here is the html:
<html ng-app="HelloApp">
<body ng-controller = "searchbarcontroller">
<search-bar/>
</body>
</html>
I am getting the error scope.search is undefined
. How can I fix my code to make it work?
search
is once your model in your input and once a function, I think you don't want to do that ;) can't you move (and rename!!!) the search function into the directive? – Betty St Jun 28 '15 at 17:53