Created
May 24, 2014 13:23
-
-
Save ThomasBurleson/004093a9292f305d932c 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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