Skip to content

Instantly share code, notes, and snippets.

@weihanchen
Created August 10, 2016 01:39
Show Gist options
  • Save weihanchen/89779a0eebaaa97621cd5d3d26ae5e01 to your computer and use it in GitHub Desktop.
Save weihanchen/89779a0eebaaa97621cd5d3d26ae5e01 to your computer and use it in GitHub Desktop.
angular input focus
'use strict';
(function() {
angular.module('notes')
.controller('focusController', [focusController])
function focusController() {
var self = this;
self.add = add;
self.inputFocus = true;
self.items = [
{ "title": "旅遊" }
]
self.unfocus = unfocus;
self.value = "";
function add(title) {
self.inputFocus = true;
if (angular.isUndefined(title) || title.length <= 0) return;
var item = { "title": title };
self.items.push(item);
self.value = "";
}
function unfocus() {
self.inputFocus = false;
}
}
})();
(function(){
angular.module('notes')
.directive('focus',focus)
function focus($parse,$timeout){
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focus);
scope.$watch(model, function(value) {
if(value === true) {
$timeout(function() {
element[0].focus();
});
}
});
element.bind('blur', function() {
scope.$apply(model.assign(scope, false));
});
}
};
}
})()
<form class="form-inline">
<div class="form-group">
<label>清單名稱:</label>
<input type="text" class="form-control" ng-model="focusCtrl.value" placeholder="請輸入清單名稱..." focus="focusCtrl.inputFocus">
</div>
<button type="submit" class="btn btn-default" ng-click="focusCtrl.add(focusCtrl.value)">add</button>
<button type="button" class="btn btn-default" ng-click="focusCtrl.unfocus()">unfocus</button>
</form>
<ul class="list-group">
<li class="list-group-item" ng-repeat="item in focusCtrl.items"></li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment