Angular ng-blur not working with ng-hide - angularjs

Using a directive focus-me="inTextModeInput" in a text input
app.directive('focusMe', function($timeout) {
/*focuses on input
<input type="text" focus-me="focusInput">
*/
return {
scope: { trigger: '=focusMe' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === true) {
$timeout(function() {
element[0].focus();
scope.trigger = false;
});
}
});
}
};
});
Actually having 2 inputs, both uses focus-me
When i programatically set the value to focus on an input the ng-blur of other is not called.
NOTE : i am also using this in an ng-repeat.

Isolated scope
The blur is called, but you're not seeing that because you've created a directive with an isolated scope. The ng-blur is executed on the $parent scope. You should only use an isolated scope when the directive is implementing re-useable templates.
Two way binding on trigger
The line 'scope.trigger = false' is also setting a different boolean value because it's on a different scope. If you want to assign a value to a variable from a directive you should always wrap the value inside another object: var focus = { me: true } and set it like trigger=focus.me.
A better solution
But I wouldn't set the trigger to false at all. AngularJS is a MVC/MVVM based framework which has a model state for the user interface. This state should be idempotent; meaning that if you store the current state, reload the page and restore the state the user interface should be in the exact same situation as before.
So what you probably need is a directive that
Has no isolated scope (which allows all other directives to work: ng-blur, ng-focus, ...)
Keeps track of a boolean, which indicates the focus state
Sets this boolean to false when the element has lost focus
It's probably easier to see this thing in action: working plunker.
Maybe this (other) plunker will give you some more insight on scopes and directives.
Code
myApp.directive('myFocus', function($parse, $timeout) {
return {
restrict: 'A',
link: function myFocusLink($scope, $element, $attrs, ctrls) {
var e = $element[0];
// Grab a parser from the provided expression so we can
// read and assign a value to it.
var getModel = $parse($attrs.myFocus);
var setModel = getModel.assign;
// Watch the parser -- and focus if true or blur otherwise.
$scope.$watch(getModel, function(value) {
if(value) {
e.focus();
} else {
e.blur();
}
});
function onBlur() {
$timeout(function() {
setModel($scope, false);
});
}
function onFocus() {
$timeout(function() {
setModel($scope, true);
});
}
$element.on('focus', onFocus);
$element.on('blur', onBlur);
// Cleanup event registration if the scope is destroyed
$scope.$on('$destroy', function() {
$element.off('focus', onFocus);
$element.off('blur', onBlur);
});
}
};
});

Related

Angularjs form $error is not getting updated when the model is updated inside a directive unless the model be cleared

I can't figure out what's happening in the following example. I just trying to create my own required validation in my own directive where I have an array and I want to make it required (it's a simplification of what I want to do but enough to show the point)
Fiddler: http://jsfiddle.net/gsubiran/p3zxkqwe/3/
angular.module('myApp', [])
.directive('myDirective', function($timeout) {
return {
restrict: 'EA',
require: 'ngModel',
controller: 'myDirectiveController',
controllerAs: 'D_MD',
link: function(scope, element, attrs, ngModel) {
ngModel.$validators.required = function(modelValue) {
var result = false;
if (modelValue && modelValue.length > 0)
result = true;
return result;
};
},
bindToController: {
ngModel: '='
},
template: '(<span>ArrayLength:{{D_MD.ngModel.length}}</span>)<br /><input type=button value="add (inside directive)" ng-click=D_MD.AddElem() /><br /><input value="clear (inside directive)" type=button ng-click=D_MD.Clear() />'
}; }) .controller('myDirectiveController', [function() {
var CTX = this;
//debugger;
//CTX.ngModel = "pipo";
CTX.clearModel = function() {
CTX.ngModel = [];
};
CTX.AddElem = function() {
CTX.ngModel.push({
Name: 'obj100',
Value: 100
});
};
CTX.Clear = function() {
CTX.ngModel = [];
}; }]) .controller('MainCtrl', function($scope) {
var CTX = this;
CTX.patito = 'donde esta el patito';
CTX.arrayElements = [];
CTX.setElements = function() {
CTX.arrayElements = [{
Name: 'obj0',
Value: 0
}, {
Name: 'obj1',
Value: 1
}, {
Name: 'obj2',
Value: 2
}];
};
CTX.clearElements = function() {
CTX.arrayElements = [];
}; })
When I hit the add (outside directive) button, the required works fine,
but when I hit the add (inside directive) button I still getting the required error in the form (the form is defined outside directive).
But the more confusing thing for me is the following:
When I hit the clear (inside directive) button after hitting add (outside directive) button to make the required error go out, in this case the form is updating and the validation error is showing.
Why $validations.required is not firing inside the directive when I add new element to array but yes when I clear it?
Any ideas?
******* UPDATE *******
It seems to be related with array.push if I change array.push with the assignation of new array with wanted elements inside it works ok.
Still the question why it is happening.
As workaround I changed in the directive the AddElem function in this way:
CTX.AddElem = function() {
CTX.ngModel = CTX.ngModel.concat({
Name: 'obj100',
Value: 100
});
};
The ngModel you use here is a JS object. Angular has a reference to that object in its $modelValue and $viewValue (because angular basically does $viewValue = $modelValue). The $modelValue is the actual value of the ngModel, which, if you change it, will change the $viewValue after having run $validators.
To know if your ngModel has Changed, angular compares the ngModel.$viewValue with the ngModel.$modelValue. Here, you are doing a push() to the $viewValue which is updating the $modelValue at the same time because they are just references of each other. Therefore, when comparing them, they have the same value ! Which is why angular does not run your $validator.
The docs explain it :
Since ng-model does not do a deep watch, $render() is only invoked if the values of $modelValue and $viewValue are actually different from their previous values. If $modelValue or $viewValue are objects (rather than a string or number) then $render() will not be invoked if you only change a property on the objects.
If I over-simplify angular code, this snippet explains it:
var myArray = [];
var ngModel = {
$viewValue: myArray,
$modelValue: myArray,
$validate: function () { console.log('validators updated'); }, // log when validators are updated
}
function $apply() { // the function that is called on the scope
if (ngModel.$viewValue !== ngModel.$modelValue) {
ngModel.$viewValue = ngModel.$modelValue;
ngModel.$validate(); // this will trigger your validator
} else {
console.log('value not changed'); // the new value is no different than before, do not call $validate
}
}
// your push is like doing :
ngModel.$viewValue.push(12);
$apply(); // will output 'value not changed', because we changed the view value as well as the model value
// whereas your should do:
var newArray = [];
// create a copy of the array (you can use angular.copy)
for (var i = 0; i < myArray.length; i++) {
newArray.push(myArray[i]);
}
ngModel.$viewValue.push(12);
ngModel.$viewValue = newArray; // here we clearly update the $viewValue without changing the model value
$apply(); // will output 'validators updated'
Of course you are not forced to do an array copy. Instead, you can force the update of your ngModel. This is done by calling ngModel.$validate();
One way of doing it would be to add a forceUpdate() function in your scope, and call it from the controller after you do a push();
Example: http://jsfiddle.net/L7Lxkq1f/

Open AngularUI Bootstrap Typeahead Matches Results via Controller

Is there anyway to trigger opening the match results on a typeahead input text box from the controller?
use case:
user goes to https://example.com/search/searchText
controller of page sets the input text to "searchText" (ng-model) on initialization
trigger showing the typeahead results from the controller
I can only seem to get the typeahead results, obviously, while typing in the input text box.
I got it to work in a couple ways, but both require changes to ui-bootstrap. I suppose I could create a pull request but not sure if my particular use case is a common one.
1) Custom directive and calling UibTypeaheadController.scheduleSearchWithTimeout method on focus of input element.
Directive:
.directive("showSearchResultsOnFocus", function($stateParams) {
return {
require: ['uibTypeahead', 'ngModel'],
link: function (scope, element, attr, ctrls) {
var typeaheadCtrl = ctrls[0];
var modelCtrl = ctrls[1];
element.bind('focus', function () {
if (!$stateParams.search || !modelCtrl.$viewValue) return;
typeaheadCtrl.exportScheduleSearchWithTimeout(modelCtrl.$viewValue);
});
}
}
Update to ui-bootstrap:
this.exportScheduleSearchWithTimeout = function(inputValue) {
return scheduleSearchWithTimeout(inputValue);
};
Bad: Requires making the method public on controller. Only method available is the init method and scope is isolated. Not meant to call from outside controller.
2) Add new typeahead attribute to allow setting default value and show results on focus:
Update to ui-bootstrap:
var isAllowedDefaultOnFocus = originalScope.$eval(attrs.typeaheadAllowDefaultOnFocus) !== false;
originalScope.$watch(attrs.typeaheadAllowedDefaultOnFocus, function (newVal) {
isAllowedDefaultOnFocus = newVal !== false;
});
element.bind('focus', function (evt) {
hasFocus = true;
// this was line before: if (minLength === 0 && !modelCtrl.$viewValue) {
if ((minLength === 0 && !modelCtrl.$viewValue) || isAllowedDefaultOnFocus) {
$timeout(function() {
getMatchesAsync(modelCtrl.$viewValue, evt);
}, 0);
}
});
Bad: Pull Request to ui-bootstrap but change perhaps not a common use feature. Submitted a PR here: https://github.com/angular-ui/bootstrap/pull/6353 Not sure if will be merged or not but using fork until then.
Any other suggestions?
Versions
Angular: 1.5.8, UIBS: 2.2.0, Bootstrap: 3.3.7

AngularJS directive doesn't update scope value even with apply

I'm usin a directive to show a div on the screen only when the screen size is smaller than 600px. The problem is, the scope value isn't being updated, even using $apply() inside the directive.
This is the code:
function showBlock($window,$timeout) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
scope.isBlock = false;
checkScreen();
function checkScreen() {
var wid = $window.innerWidth;
if (wid <= 600) {
if(!scope.isBlock) {
$timeout(function() {
scope.isBlock = true;
scope.$apply();
}, 100);
};
} else if (wid > 600) {
if(scope.isBlock) {
$timeout(function() {
scope.isBlock = false;
scope.$apply();
}, 100);
};
};
};
angular.element($window).bind('resize', function(){
checkScreen();
});
}
};
}
html:
<div ng-if="isBlock" show-block>
//..conent to show
</div>
<div ng-if="!isBlock" show-block>
//..other conent to show
</div>
Note: If I don't use $timeout I'll get the error
$digest already in progress
I used console logs inside to check if it's updating the value, and inside the directive everything works fine. But the changes doesn't go to the view. The block doesn't show.
You should use do rule in such cases to get the advantage of Prototypal Inheritance of AngularJS.
Basically you need to create a object, that will will have various property. Like in your case you could have $scope.model = {} and then place isBlock property inside it. So that when you are inside your directive, you will get access to parent scope. The reason behind it is, you are having scope: true, which says that the which has been created in directive is prototypically inherited from parent scope. That means all the reference type objects are available in your child scope.
Markup
<div ng-if="model.isBlock" show-block>
//..conent to show
</div>
<div ng-if="!model.isBlock" show-block>
//..other conent to show
</div>
Controller
app.controller('myCtrl', function($scope){
//your controller code here
//here you can have object defined here so that it can have properties in it
//and child scope will get access to it.
$scope.model = {}; //this is must to use dot rule,
//instead of toggle property here you could do it from directive too
$scope.isBlock = false; //just for demonstration purpose
});
and then inside your directive you should use scope.model.isBlock instead of scope.isBlock
Update
As you are using controllerAs pattern inside your code, you need to use scope.ag.model.isBlock. which will provide you an access to get that scope variable value inside your directive.
Basically you can get the parent controller value(used controllerAs pattern) make available controller value inside the child one. You can find object with your controller alias inside the $scope. Like here you have created ag as controller alias, so you need to do scope.ag.model to get the model value inside directive link function.
NOTE
You don't need to use $apply with $timeout, which may throw an error $apply in progress, so $timeout will run digest for you, you don't need to worry about to run digest.
Demo Here
I suspect it has something to do with the fact that the show-block directive wouldn't be fired if ng-if="isBlock" is never true, so it would never register the resize event.
In my experience linear code never works well with dynamic DOM properties such as window sizing. With code that is looking for screens size you need to put that in some sort of event / DOM observer e.g. in angular I'd use a $watch to observe the the dimensions. So to fix this you need to place you code in a $watch e.g below. I have not tested this code, just directional. You can watch $window.innerWidth or you can watch $element e.g. body depending on your objective. I say this as screens will be all over the place but if you control a DOM element, such as, body you have better control. also I've not use $timeout for brevity sake.
// watch window width
showBlock.$inject = ['$window'];
function bodyOverflow($window) {
var isBlock = false;
return {
restrict: 'EA',
link: function ($scope, element, attrs) {
$scope.$watch($window.innerWidth, function (newWidth, oldWidth) {
if (newWidth !== oldWidth) {
return isBlock = newWidth <= 600;
}
})
}
};
}
// OR watch element width
showBlock.$inject = [];
function bodyOverflow() {
var isBlock = false;
return {
restrict: 'EA',
link: function ($scope, element, attrs) {
$scope.$watch($element, function (new, old) {
if (newWidth) {
return isBlock = newWidth[0].offsetWidth <= 600;
}
})
}
};
}

JQuery UI Spinner is not updating ng-model in angular

Angular's ng-model is not updating when using jquery-ui spinner.
Here is the jsfiddle http://jsfiddle.net/gCzg7/1/
<div ng-app>
<div ng-controller="SpinnerCtrl">
<input type="text" id="spinner" ng-model="spinner"/><br/>
Value: {{spinner}}
</div>
</div>
<script>
$('#spinner').spinner({});
</script>
If you update the text box by typing it works fine (you can see the text change). But if you use the up or down arrows the model does not change.
Late answer, but... there's a very simple and clean "Angular way" to make sure that the spinner's spin events handle the update against ngModel without resorting to $apply (and especially without resorting to $parse or an emulation thereof).
All you need to do is define a very small directive with two traits:
The directive is placed as an attribute on the input element you want to turn into a spinner; and
The directive configures the spinner such that the spin event listener calls the ngModel controller's $setViewValue method with the spin event value.
Here's the directive in all its clear, tiny glory:
function jqSpinner() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, c) {
element.spinner({
spin: function (event, ui) {
c.$setViewValue(ui.value);
}
});
}
};
};
Note that $setViewValue is intended for exactly this situation:
This method should be called when an input directive wants to change
the view value; typically, this is done from within a DOM event
handler.
Here's a link to a working demo.
If the demo link provided above dies for some reason, here's the full example script:
(function () {
'use strict';
angular.module('ExampleApp', [])
.controller('ExampleController', ExampleController)
.directive('jqSpinner', jqSpinner);
function ExampleController() {
var c = this;
c.exampleValue = 123;
};
function jqSpinner() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, c) {
element.spinner({
spin: function (event, ui) {
c.$setViewValue(ui.value);
}
});
}
};
};
})();
And the minimal example template:
<div ng-app="ExampleApp" ng-controller="ExampleController as c">
<input jq-spinner ng-model="c.exampleValue" />
<p>{{c.exampleValue}}</p>
</div>
Your fiddle is showing something else.
Besides this: Angular can not know about any changes that occur from outside its scope without being aknowledged.
If you change a variable of the angular-scope from OUTSIDE angular, you need to call the apply()-Method to make Angular recognize those changes. Despite that implementing a spinner can be easily achieved with angular itself, in your case you must:
1. Move the spinner inside the SpinnerCtrl
2. Add the following to the SpinnerCtrl:
$('#spinner').spinner({
change: function( event, ui ) {
$scope.apply();
}
}
If you really need or want the jQuery-Plugin, then its probably best to not even have it in the controller itself, but put it inside a directive, since all DOM-Manipulation is ment to happen within directives in angular. But this is something that the AngularJS-Tutorials will also tell you.
Charminbear is right about needing $scope.$apply(). Their were several problems with this approach however. The 'change' event only fires when the spinner's focus is removed. So you have to click the spinner then click somewhere else. The 'spin' event is fired on each click. In addition, the model needs to be updated before $scope.$apply() is called.
Here is a working jsfiddle http://jsfiddle.net/3PVdE/
$timeout(function () {
$('#spinner').spinner({
spin: function (event, ui) {
var mdlAttr = $(this).attr('ng-model').split(".");
if (mdlAttr.length > 1) {
var objAttr = mdlAttr[mdlAttr.length - 1];
var s = $scope[mdlAttr[0]];
for (var i = 0; i < mdlAttr.length - 2; i++) {
s = s[mdlAttr[i]];
}
s[objAttr] = ui.value;
} else {
$scope[mdlAttr[0]] = ui.value;
}
$scope.$apply();
}
}, 0);
});
Here's a similar question and approach https://stackoverflow.com/a/12167566/584761
as #Charminbear said angular is not aware of the change.
However the problem is not angular is not aware of a change to the model rather that it is not aware to the change of the input.
here is a directive that fixes that:
directives.directive('numeric', function() {
return function(scope, element, attrs) {
$(element).spinner({
change: function(event, ui) {
$(element).change();
}
});
};
});
by running $(element).change() you inform angular that the input has changed and then angular updates the model and rebinds.
note change runs on blur of the input this might not be what you want.
I know I'm late to the party, but I do it by updating the model with the ui.value in the spin event. Here's the updated fiddle.
function SpinnerCtrl($scope, $timeout) {
$timeout(function () {
$('#spinner').spinner({
spin: function (event, ui) {
$scope.spinner = ui.value;
$scope.$apply();
}
}, 0);
});
}
If this method is "wrong", any suggestions would be appreciated.
Here is a solution that updates the model like coder’s solution, but it uses $parse instead of parsing the ng-model parameter itself.
app.directive('spinner', function($parse) {
return function(scope, element, attrs) {
$(element).spinner({
spin: function(event, ui) {
setTimeout(function() {
scope.$apply(function() {
scope._spinnerVal = = element.val();
$parse(attrs.ngModel + "=_spinnerVal")(scope);
delete scope._spinnerVal;
});
}, 0);
}
});
};
});

Get value of scope variable in controller AngularJS

I have to fetch value of scope variable defined in directives. I have to get value of that scope variable in controller using AngularJS. How can i fetch value of scope variable?
Directive
app.directive('checkToggle', function() {
return {
scope: true,
link: function ($scope, element, attrs) {
$(element).on('click', function() {
$(element).find('i').toggleClass('icon-check icon-check-empty');
if ($(element).find('i').hasClass('icon-check')) {
$scope.isChecked = 'true';
} else {
$scope.isChecked = 'false';
}
});
}
}
});
I have to get $scope.isChecked value in controller.
If I understand your use-case correctly you would like to toggle an icon on click. If so you don't need to write any directive for this. And provided that you would like to write a directive your shouldn't go about it as you've started. Your code is very imperative, jQuery-like while AngularJS power is in driving declarative UI based on model changes.
Anyway, toggling an icon can be easily done with standard AngularJS directives:
<i ng-class="{'icon-star' : isChecked, 'icon-star-empty': !isChecked}" ng-click="isChecked = !isChecked"></i>
Here is a working plunk: http://plnkr.co/edit/nXXQA41w00Cpeo6tTibg?p=preview

Resources