I have the following directive:
app.directive('onFileSelected', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element[0]._HANDLE = scope.$eval(attrs.onFileSelected);
element.bind('change', function() {
element[0]._HANDLE();
});
}
};
});
And now, the following html:
<input type="file" name="{{container._id}}" on-file-selected="FileChanged" style="display: block !important;"/>
<div ng-repeat="item in container.items">
<input type="file" name="{{container._id}}" on-file-selected="FileChanged" style="display: block !important;"/>
</div>
In my scope, i have defined the following method:
$scope.container = {
_id: 0,
items: [1,2,3,4,5]
};
$scope.FileChanged = function() {
alert(this.files.length);
};
The Problem is now: This directive works only inside the ng-repeat, but not outside. Any ideas? Am I missing something? Outside of ng-repeat scope.$eval(attrs.onFileSelected); returns undefined.
Thank you!
Related
I want to take a response from a web service and apply it to the ng-options inside the angular.forEach loop. All I think I have to access it is the element itself. Here is the code. Normally I would just write:
scope.whatIWantTheOptionsToB = DBResponse;
But inside the forEach loop I can't do that. How would I set the options variable inside the for each loop.
Here is my code so far:
HTML:
<div class="form__row">
<label>Injury Type:</label>
<select
class="form__select"
ws="populateDDL"
param="tblInjuryTypes"
ng-model="injuryType_id"
ng-options="injury.id as injury.name for injury in injuryTypes"
ng-change="injuryUpdate()"
name="injuryTypes"
required
></select>
</div>
<div class="form__row">
<label>Work Status:</label>
<select
class="form__select"
ws="populateDDL"
param="tblWorkStatus"
ng-model="workStatus_id"
ng-options="status.id as status.name for status in workStatus"
name="workStatus"
required
></select>
</div>
Directive:
app.directive(
'providerForm',
['$http', 'populateDDL', 'classHandler', function ($http, populateDDL, classHandler){
var directive = {
link: link,
scope: true,
restrict: 'E',
templateUrl: '/modules/providerForm.html',
};
return directive;
function link(scope, element, attrs, ctrl) {
var selects = element.find('select');
angular.forEach(selects, function(e,i) {
if (e.attributes['ws'].value === 'populateDDL') {
scope.data = {
sKey: sessionStorage.getItem('key'),
sTableName: e.attributes['param'].value,
iInjuryTypeId: scope.injuryType_id,
iBodyPartId: scope.bodyPart_id
};
scope.getSelectOptions = new populateDDL(e.attributes['ws'].value, scope.data).
then(function(response) {
console.log(e)
scope.whatIWantTheOptionsToBeEachTimeThru = response;
});
}
});
}
}]
);
I want to reset this directive(clear the file chosen) when clear button is clicked. Currently even though when clear button is clicked , the file chosen is still exits and its not cleared.
test.html
<form class="form form-basic" id="testForm" name="testForm">
<div class="row">
<label class="col-md-6 control-label">File :</label>
<div class="col-md-6">
<div class="form-group">
<input type="file" ng-model="test" on-read-file="loadContent($fileContent)" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-click="clear()">Clear</button>
</div>
directive.js
fileAccessModule.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function (scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function (onChangeEvent) {
var reader = new FileReader();
reader.onload = function (onLoadEvent) {
scope.$apply(function () {
fn(scope, {$fileContent: onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
testController.js
testControllerModule.controller('testController', function ($scope, $log, $location, deviceDetailsService) {
$scope.clear = function () {
$scope.connectionParams = null;
};
$scope.loadContent = function ($fileContent) {
$scope.connectionParams.privateKey = $fileContent;
};
});
Not sure what $scope.connectionParams is that by setting it to null, you are expecting the form to be reset.
However, to achieve the same form reset logic, you can resort to Javascript's built-in reset() method, but, in an Angularized manner.
To do so, you can define a directive for this as such:
/* ... */
.directive('formReset', function() {
return {
restrict: 'E',
replace: true,
scope: {
formName: '#'
},
link: function(scope, iElement) {
iElement.on('click', function() {
var form = document.querySelector('[name="' + scope.formName + '"]');
form.reset();
});
}
},
template: '<button type="button">Reset</button>'
})
and, use it in your form as in the following:
<form-reset form-name="yourFormName"></form-reset>
Demo
I have a directive, with an attribute :
html :
<my-directive id="test" myattr="50"></my-directive>
js :
myApp.directive('myDirective', function() {
var link = function(scope, element, attrs) {
scope.$watch('myattr', function(value) {
element.attr('myattr', value);
});
scope.change = function() {
// some code
};
};
return {
restrict: 'E',
template: '<input type="text" ng-change="change()" ng-model="myattr"/>',
scope: {myattr: '='},
link: link
};
});
My goal would be to keep myattr and the value of the input equal. With element.attr('myattr', value) I can force myattr to have the correct value, but how am I supposed to update the input when myattr changes?
For example, in this jsfiddle, when clicking on the button, I try to do :
$('#test').attr('myattr', Math.random() * 100);
But I can't find a way to 'catch' the change from within the directive.
I would like some help modifying the jsfiddle so that :
the function change is called after the jquery call.
the value of the input is always equal to myattr
You need to store the value of myattr as a property on a scope not as a value on an attribute.
Your directive is correct you need to also attach a controller.
var myApp = angular.module('myApp', []);
myApp.controller('MainController', function ($scope) {
$scope.calculate = function () {
// your logic here
alert($scope.val);
}
});
myApp.directive('myDirective', function() {
var link = function(scope, element, attrs) {
scope.change = function() {
console.log("change " + scope.myattr);
};
};
return {
restrict: 'E',
template: '<input type="text" ng-change="change()" ng-model="myattr"/>',
scope: {
myattr: '='
},
link: link
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainController">
My Value: {{val}} <br/>
<button type="button" ng-click="calculate()">ok</button>
<my-directive id="test" myattr="val"></my-directive>
</div>
</div>
I'm a bit stuck on an directive which add attributes and recompile the element.
If I had a scope on the directive ng-change is not triggered anymore (without it it works). I based my test on this answer
The HTML
<div ng-app="myApp">
<div ng-controller='testController'>
<div ng-repeat="field in fields">
<input type="text" ng-model="ngModel[field.fieldName]" property="{{formParams.getProperties(field.fieldName)}}" update-attr ng-change="test()" />
</div>
</div>
</div>
The directive:
angular.module('myApp', [])
.controller('testController', function ($scope) {
$scope.properties = {
"something": {
"style": "float:left;"
},
"something2": {
"style": "float:right;"
}
};
$scope.ngModel = {};
$scope.fields = [{
fieldName: 'something'
}, {
fieldName: 'something2'
}];
$scope.test = function () {
alert('i dont get triggered');
};
$scope.formParams = {
getProperties: function (fieldName) {
return $scope.properties[fieldName];
}
};
})
.directive('updateAttr', function ($compile) {
return {
restrict: 'A',
replace: true,
terminate: true,
scope: {
ngModel : '='
},
link: function (scope, elem, attrs) {
if (angular.isDefined(attrs['property']) && attrs['property'].lenght != 0) {
var json = JSON.parse(attrs['property']);
angular.forEach(json, function (value, key) {
elem.attr(key, value);
});
elem.removeAttr('property');
var $e = $compile(elem[0].outerHTML)(scope);
elem.replaceWith($e);
}
}
};
});
Here a fork of the fiddle to test with a scope on the directive: fiddle
Do you have any suggestion ?
I found why ng-change was not trigger so I share the answer:
When we add scope attribute on the directive, a new scope is created. So we have to use $scope.$parent for the compilation. I have updated the fiddle with the correction.
I have places in my code where I have this:
<input data-ng-disabled="SOME_SCOPE_VARIABLE" />
I would like to be able to use it like this too:
<input data-ng-autofocus="SOME_SCOPE_VARIABLE" />
Or even better, mimicking how ng-style is done:
<input data-ng-attribute="{autofocus: SOME_SCOPE_VARIABLE}" />
Does this exist in the current version of AngularJS? I noticed in the code there's a BOOLEAN_ATTR which gets all the attr's that AngularJS supports. I don't want to modify that in fear of changing versions and forgetting to update.
Update: AngularJS now has an ngFocus directive that evaluates an expression on focus, but I mention it here for the sake of completeness.
The current version of AngularJS doesn't have a focus directive, but it's in the roadmap. Coincidentally, we were talking about this on the mailing list yesterday, and I came up with this:
angular.module('ng').directive('ngFocus', function($timeout) {
return {
link: function ( scope, element, attrs ) {
scope.$watch( attrs.ngFocus, function ( val ) {
if ( angular.isDefined( val ) && val ) {
$timeout( function () { element[0].focus(); } );
}
}, true);
element.bind('blur', function () {
if ( angular.isDefined( attrs.ngFocusLost ) ) {
scope.$apply( attrs.ngFocusLost );
}
});
}
};
});
Which works off a scope variable as you requested:
<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">
Here's a fiddle: http://jsfiddle.net/ANfJZ/39/
You can do this with the built-in ngAttr attribute bindings.
<input ng-attr-autofocus="{{SOME_SCOPE_VARIABLE}}">
The autofocus attribute will be added if SOME_SCOPE_VARIABLE is defined (even if it's false), and will be removed if it's undefined. So I force falsy values to be undefined.
$scope.SOME_SCOPE_VARIABLE = someVar || undefined;
This directive should do the trick:
angular.module('utils.autofocus', [])
.directive('autofocus', ['$timeout', function($timeout) {
return {
restrict: 'A',
scope: {'autofocus':'='}
link : function($scope, $element) {
$scope.$watch 'autofocus', function(focus){
if(focus){
$timeout(function() {
$element[0].focus();
});
}
}
}
}
}]);
Taken from here: https://gist.github.com/mlynch/dd407b93ed288d499778
scope.doFocus = function () {
$timeout(function () {
document.getElementById('you_input_id').focus();
});
};
Create a directive like this
.directive('autoFocus', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function ($scope, $element) {
$timeout(function () {
$element[0].focus();
});
}
}
<input type="text" auto-focus class="form-control msd-elastic" placeholder="">
What I did is using regular autofocus on my inputs: <input autofocus>
And then I set the focus on the first visible input with autofocus when angular is ready:
angular.element(document).ready(function() {
$('input[autofocus]:visible:first').focus();
});
Hope this helps.
I did it with two custom directives, something like this:
(function(angular) {
'use strict';
/* #ngInject */
function myAutoFocus($timeout) {
return {
restrict: 'A',
link: function(scope, element) {
$timeout(function() {
element[0].focus();
}, 300);
}
};
}
function myFocusable() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var focusMethodName = attrs.myFocusable;
scope[focusMethodName] = function() {
element[0].focus();
};
}
};
}
angular
.module('myFocusUtils', [])
.directive('myAutoFocus', myAutoFocus)
.directive('myFocusable', myFocusable);
}(angular));
If you add attribute my-auto-focus to an element, it will receive focus after 300ms. I set the value to 300 instead of 0 to let other async components to load before setting the focus.
The attribute my-focusable will create a function in the current scope. This function will set focus to the element when called. As it creates something in the scope, be cautious to avoid overriding something.
This way you don't need to add something to Angular's digest cycle (watch) and can do it entirely in the view:
<input my-focusable="focusOnInput"></input>
<button ng-click="focusOnInput()">Click to focus</button>
I created a JSFiddle to show the myFocusable directive: http://jsfiddle.net/8shLj3jc/
For some reason I don't know, the myAutoFocus directive does not work in JSFiddle, but it works in my page.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<div ng-repeat="x in names">
<input ng-attr-focus={{$first}} value="{{x.name + ', ' + x.country }}" />
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('namesCtrl', function($scope) {
$scope.names = [
{name:'x1',country:'y1'},
{name:'x2',country:'y2'},
{name:'x3',country:'y3'}
];
});
myApp.directive("focus", function(){
return {
restrict: "A",
link: function link(scope, element, attrs) {
if(JSON.parse(attrs.focus)){
element[0].focus();
}
}
};
});
</script>
</body>
</html>
had created above custom directive for one of my use case.
always focusses on first input element.
works for ajax data, browser back/forward buttons.
Tested on chrome and firefox(default autofocus is not supported here)
JSON.parse is used to parse string "true" returned from html to boolean true in JS.
another way to use attrs.focus === "true" for if condition.
so without $timeout you can also use auto focus like this -
<input type="text" ng-show="{{condition}}" class='input-class'></input>
angular.element(document).ready(function(){
angular.element('.input-class')[0].focus();
});
Combining whar others mentioned above:
JS Code:
myApp.directive('ngAutofocus', ['$timeout', function ($timeout) {
var linker = function ($scope, element, attrs) {
$scope.$watch('pageLoaded', function (pageLoaded) {
if (pageLoaded) {
$timeout(function () {
element[0].focus();
});
}
});
};
return {
restrict: 'A',
link: linker
};
}]);
HTML:
<input type="text" ng-model="myField" class="input-block-level edit-item" ng-autofocus>
Set pageLoaded to true from your initial load method of the page get:
var loadData = function () {
..
return $http.get(url).then(function (requestResponse) {
$scope.pageLoaded = true;
......
}