Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibot17/d25c0e60280cfc99aad0 to your computer and use it in GitHub Desktop.
Save guibot17/d25c0e60280cfc99aad0 to your computer and use it in GitHub Desktop.
Sample of using AngularJS MySearchboxDirective. This demonstrates some fixes for the example demonstrated in the slides http://slides.com/djsmith/deep-dive-into-custom-directives
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin-left : 15px;
margin-top: 15px;
}
input {
padding-left: 10px;
}
</style>
</head>
<body ng-app="djsmith.sample" ng-controller="SampleController">
<!-- @see http://slides.com/djsmith/deep-dive-into-custom-directives -->
<p>
Searching: <input type="text" ng-model="criteria" placeholder="{{placeholder}}" style="margin-left: 10px;" />
</p>
<my-searchbox
search-text="criteria"
placeholder="Please search now" >
</my-searchbox>
<script src="//code.angularjs.org/1.3.0-beta.9/angular.min.js"></script>
<script>
(function( ){
"use strict";
angular.module( 'djsmith.sample', [ ] )
.controller( 'SampleController', function SampleController($scope){
$scope.criteria = "ThomasB";
})
.directive( 'mySearchbox', function mySearchboxDirective( )
{
return {
restrict: 'E',
scope: {
searchText: '=',
placeholder: '@',
},
link: function($scope, element, attrs) {
watchSearchText($scope);
$scope.searchClicked = function() {
$scope.searchText = $scope.tempSearchText;
}
$scope.luckyClicked = function() {
$scope.searchText = $scope.tempSearchText;
}
},
template:
'<div>' +
' <input type="text" ng-model="tempSearchText" placeholder="{{placeholder}}" />' +
' <button ng-click="searchClicked()">' +
' Search' +
' </button>' +
' <button ng-click="luckyClicked()">' +
' I\'m feeling lucky' +
' </button>' +
'</div>'
};
// **********************************************************
// Private Methods
// **********************************************************
/**
* Watch our internal scope `searchText` to keep our directive's search input box
* synchronized; since it watches `tempSearchText`.
* @param $scope
*/
function watchSearchText($scope)
{
var unwatch;
$scope.tempSearchText = $scope.searchText;
unwatch = $scope.$watch('searchText', function( searchText ){
$scope.tempSearchText = searchText;
});
$scope.$on( "$destroy", unwatch );
}
});
})( );
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment