我有一个带有输入框的简单应用程序,如果用户在输入框中键入内容,则每次用户输入内容时都会触发警报消息(使用密钥)。
我想在输入框中使用指令(称为searchBar),并在每次输入内容时调用控制器函数。
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());
};
}]);
这是html:
<html ng-app="HelloApp">
<body ng-controller = "searchbarcontroller">
<search-bar/>
</body>
</html>
我收到错误scope.search is undefined
。如何修复我的代码才能使其正常工作?
答案 0 :(得分:3)
HTML:
<div ng-app="HelloApp">
<div ng-controller="MyCtrl">
<search-bar/>
</div>
</div>
JS:
var app = angular.module('HelloApp', []);
app.directive('searchBar', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="searchData" placeholder="Enter a search" />',
link: function(scope, elem, attrs) {
elem.bind('keyup', function() {
elem.css('background-color', 'red');
scope.$apply(function() {
scope.search(elem);
});
});
}
};
});
app.controller('MyCtrl', function($scope) {
$scope.search = function(element) {
console.log(element);
alert("keypressed. Value so far is: " + element.val());
};
});
答案 1 :(得分:0)
这是一个工作小提琴:http://jsfiddle.net/36qp9ekL/365/
app.directive('searchBar', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="query" ng-click="search(query)" placeholder="Enter a search" />',
link: function(scope, elem, attrs) {
elem.bind('keyup', function() {
elem.css('background-color', 'white');
scope.$apply(function() {
scope.search(elem);
});
});
}
};
});
搜索曾被用作模型,然后用作函数。您可能不需要keyup的指令,因为angular具有内置的ng-blur。请参阅:https://docs.angularjs.org/api/ng/directive/ngBlur
答案 2 :(得分:0)
如果你想重用,那么你可以在这里使用隔离范围,只需要将方法传递给指令serach-method
属性,这将绑定要在keyup
上调用的事件,以便在用户输入时什么,然后搜索方法被调用。您可以通过使用它来传递事件对象,您可以从事件对象中轻松获取target
元素的值。
<强>标记强>
<body ng-controller="searchbarcontroller">
<search-bar serach-method="search(event)"></search-bar>
</body>
<强>指令强>
app.directive('searchBar', function () {
return {
restrict: 'AE',
scope: {
serachMethod: '&'
},
replace: true,
template: '<input type="text" ng-model="search" placeholder="Enter a search" />',
link: function (scope, elem, attrs) {
elem.bind('keyup', function (event) {
elem.css('background-color', 'white');
scope.$apply(function () {
scope.serachMethod({event: event}); //calling controller method.
});
});
}
};
});
<强>控制器强>
$scope.search = function (element) {
alert("keypressed. Value so far is: " + element.target.value);
};