Angularjs How to get value of input[text] in controller - angularjs

I want to get value of input[text] in my controller when data is changed as this source code:
(function () {
'use strict';
var app = angular.module('app', ['ngMaterial']);
app.controller('ScanDataCtrl', function ($scope) {
$scope.getScannedData = function () {
console.log($scope.formScanData.scanDataIReceipt);
};
});
app.directive('scanDataBScan', function ($mdDialog, $sce, $http) {
return {
restrict: 'C',
link: function (scope, element, attrs) {
element.on('click', function () {
scope.getScannedData();
// => the value always undefined
});
}
};
});
});
<div ng-controller="ScanDataCtrl">
<form accept-charset="UTF-8" class="form-inline formScanData" name="formScanData">
<input ng-model="formScanData.scanDataIReceipt" type="text" required>
<md-input-container>
<md-button ng-model="scanDataBScan" class="md-raised md-primary scanDataBScan">Scan</md-button>
</md-input-container>
</form>
</div>
the result of this source code is always undefine
Please help me.
If I ask wrong or bad with my English, I am sorry.
Thank you!

Use the ng-change directive:
<input ng-model="formScanData.scanDataIReceipt" type="text"
ng-change="getScannedData()" required>
For more information, see AngularJS ng-change Directive API Reference.

(function () {
'use strict';
var app = angular.module('app', ['ngMaterial']);
app.controller('ScanDataCtrl', function ($scope) {
$scope.getScannedData = function (data) {
console.log(data);
};
});
app.directive('scanDataBScan', function ($mdDialog, $sce, $http) {
return {
restrict: 'C',
link: function (scope, element, attrs) {
element.on('click', function () {
scope.getScannedData();
// => the value always undefined
});
}
};
});
});
<div ng-controller="ScanDataCtrl">
<form accept-charset="UTF-8" class="form-inline formScanData" name="formScanData">
<input ng-model="formScanData.scanDataIReceipt" type="text" required>
<md-input-container>
<md-button ng-model="scanDataBScan" ng-click="getScannedData(formScanData.scanDataIReceipt)" class="md-raised md-primary scanDataBScan">Scan</md-button>
</md-input-container>
</form>
</div>

Related

Focus on textbox when radiobutton is selected in AngularJS

can someone please give me an idea on how will i set focus on my textbox when I click the radiobutton assigned to it? Im using angular js. Thanks for any idea
I created example for you.
HTML:
<body ng-app="scopeExample">
<div ng-controller="MyController">
<div ng-repeat='item in mas'>
<input type="radio" name='somename' ng-model="item.select" value="true" ng-click='clear(item)'>
<input type='text' focus='item.select'/>
<br>
</div>
</div>
</body>
Javascript:
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.mas=[
{id:1,select:false},
{id:2,select:false},
{id:3,select:false},
{id:4,select:false}
];
$scope.clear = function(item){
$scope.mas.forEach(function(x){
if(x != item)
x.select=false;
});
}
}]).directive('focus',['$timeout', '$parse', function($timeout, $parse){
return {
link:function (scope, element, attrs) {
var model = $parse(attrs['focus']);
scope.$watch(model, function (value) {
if (eval(value))
$timeout(function () {
element[0].focus();
});
});
}
}
}]);
I will provide you pseudo code which you can alter on the basis of your needs. For now, the code has one radio button which when selected will focus on the input element. However, you can achieve those on list, on checkbox as per your need.
HTML:
<div ng-controller="MyCtrl">
<input type="radio" ng-model="focusRadio" value=0>
<input ng-model="name" focus>
</div>
Script:
var myApp = angular.module('myApp',[]);
myApp.directive('focus', function() {
return function(scope, element) {
scope.$watch('focusRadio',
function (newValue) {
newValue && element[0].focus()
})
}
});
function MyCtrl($scope) {}
Here is the plunker: http://plnkr.co/edit/ABHCRIm95EyNUI8nWczh?p=preview . Change the input type to checkbox to better know about the functionality.

Pass variable to directive that is restricted to attribute

I have this directive:
.directive('myDate', ['$timeout', '$rootScope', '$locale',
function ($timeout, $rootScope, $locale) {
'use strict';
return {
restrict: 'A',
scope: {
customDate: '='
},
// the rest part of directive...
};
}
]);
I know how to pass a variable to directive that is restricted to element. But that approach doesn't work when the directive is given as attribute:
<div class="input-group date" my-date custom-date="testDate">
<input type="text" class="form-control" ng-model="dateFrom" />
</div>
Where:
scope.testDate= new Date('2015-01-13')
How can I get it work?
For the most part, your code should work. Here is a working plunker for the rest. There were just a few small issues with the OP. In the controller, the property that is bound to the directive attribute must be of the same name (scope.date should have been scope.testDate) etc.
The controller:
app.controller('Ctrl', function($scope) {
$scope.testDate = new Date('2015-01-13')
});
The directive:
app.directive('myDate', ['$timeout', '$rootScope',
function ($timeout, $rootScope) {
'use strict';
return {
restrict: 'A',
scope: {
customDate: '='
},
link(scope) {
console.log(scope.customDate);
}
};
}
]);
The HTML:
<body ng-app="myApp">
<div ng-controller="Ctrl">
<div class="input-group date" my-date custom-date="testDate">
<input type="text" class="form-control" ng-model="dateFrom" />
</div>
</div>
</body>

Validating form when directive creates form inputs dynamically

I am trying to validate form while using directive. The directive creates form inputs by compiling and replacing the element.
If I use simple template version of directive it works fine. If the input created by directive is invalid form is also invalid. It even works when created in a loop as well : http://codepen.io/kuasha/pen/gbreKP
<div ng-app="app" ng-controller="MainCtrl">
<form name="myform" ng-submit="sendForm()" novalidate>
<div class="form-group">
<myinput />
</div>
<div class="form-group">
<button ng-show="myform.$valid" type="submit">Submit!</button>
</div>
</form>
</div>
The app and controller:
var app = angular.module('app', []);
app.controller('MainCtrl', function ($scope) {
$scope.sendForm = function () {
if ($scope.myform.$valid) {
alert('form valid');
}
};
});
Here is the simple working version of the directive:
app.directive('myinput', function () {
return {
restrict: 'E',
template: '<label>Test</label><input ng-model="value" type="text" required ng-minlength="5" />'
};
});
But if I change the directive to use a link function and compile then, even when the input inside the directive is invalid, forms $valid is still true: http://codepen.io/kuasha/pen/qEZoKv?editors=101
app.directive('myinput', function ($compile) {
return {
restrict: 'E',
link: function (scope, element, attributes) {
var template = '<div><input type="text" required ng-minlength=5 /></div>'
var newElement = angular.element(template);
$compile(newElement)(scope);
element.replaceWith(newElement);
}
};
});
Edit:
Directive could create its own validator-
app.directive('myinput', function ($compile) {
return {
require:'^form',
restrict: 'E',
scope: {
},
controller: ['$scope', function($scope){
}],
link: function (scope, element, attributes, ctrl) {
var template = '<label>Test</label><input name="myctrl" ng-model="value" type="text" required ng-minlength="5" />'
var newElement = angular.element(template);
$compile(newElement)(scope);
element.replaceWith(newElement);
scope.$watch("value", function(){
ctrl.$setValidity('myctrl', scope.value && scope.value.length > 0);
console.log("Validity set");
});
}
};
});
But its probably not right approach for this particular problem.
You should switch the replaceWith and $compile (DEMO):
element.replaceWith(newElement);
$compile(newElement)(scope);
I think it is because you can't really compile an element that is not yet in the DOM. But I'm not sure.

AngularJS : How can I use an object id to create a set of form fields

edit: I worked it out, I need to use [tray.id] instead of {{tray.id}}
I have an array of "trays" and I want to build a form to edit them, but I'm not sure how to set the ng-model for each tray so I can differentiate between them.
This does not work, angular doesn't like me putting {{tray.id}} into ng-model
<div ng-repeat="tray in formData.trayData">
<div class="form-group">
<label class="control-label" for="formData.trays.{{tray.id}}.name">Name:</label>
<div class="controls">
<input type="text" class="form-control" name="tray.{{tray.id}}.name" ng-model="formData.trays.{{tray.id}}.name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="control-label" for="formData.trays.{{tray.id}}.seal">Seal:</label>
<div class="controls">
<input type="text" class="form-control" name="tray.{{tray.id}}.seal" ng-model="formData.trays.{{tray.id}}.sealed" placeholder="Seal">
</div>
</div>
</div>
In my controller I setup formData using a json object from an API
$scope.formData.trayData = $scope.surgeryDetails.trays;
$scope.formData.trays = [];
And here is what I get from {{formdata.trayData}}
[{"id":8,"name":"Tray 1","seal":"Foo","status_id":9},{"id":9,"name":"Tray 2","seal":"Bar","status_id":9}]
I'm glad you figured the ngModel part out on your own.
However, I also just wanted to mention that you may not be getting what you are expecting when/if you go to handle validation using the name attribute.
There is currently a bug in Angular that prevents dynamic element validation. The workaround is provided in the comments by Thinkscape, or here is a plunker with the correct code. Here is the main part:
angular.module('myModule', [])
.config(function($provide) {
$provide.decorator('ngModelDirective', function($delegate) {
var ngModel = $delegate[0],
controller = ngModel.controller;
ngModel.controller = ['$scope', '$element', '$attrs', '$injector',
function(scope, element, attrs, $injector) {
var $interpolate = $injector.get('$interpolate');
attrs.$set('name', $interpolate(attrs.name || '')(scope));
$injector.invoke(controller, this, {
'$scope': scope,
'$element': element,
'$attrs': attrs
});
}
];
return $delegate;
});
$provide.decorator('formDirective', function($delegate) {
var form = $delegate[0],
controller = form.controller;
form.controller = ['$scope', '$element', '$attrs', '$injector',
function(scope, element, attrs, $injector) {
var $interpolate = $injector.get('$interpolate');
attrs.$set('name', $interpolate(attrs.name || attrs.ngForm || '')(scope));
$injector.invoke(controller, this, {
'$scope': scope,
'$element': element,
'$attrs': attrs
});
}
];
return $delegate;
});
})

Angular highlight/select all content inside <div> element Angular

How do we highlight and select all content inside a element on click using Angular JS ?.
It is easy to do using inputbox. But how do we do for element.
Help would be appreciated.
Thank you
This is what I have used so far.
HTML
<div ng-controller="appController" ng-app="app">
<input type="text" ng-model="content" ng-click="onTextClick($event)" />
</div>
JS
var app = angular.module('app', []);
app.controller('appController',
function ($scope) {
$scope.content = 'test';
$scope.onTextClick = function ($event) {
$event.target.select();
};
});
http://jsfiddle.net/onury/R63u5/
jsfiddle: http://jsfiddle.net/n63LhtcL/3/
Here is an updated directive to achieve it:
.directive('selectOnClick', function ($window) {
return {
link: function (scope, element) {
element.on('click', function () {
var selection = $window.getSelection();
var range = document.createRange();
range.selectNodeContents(element[0]);
selection.removeAllRanges();
selection.addRange(range);
});
}
}
});
Your markup:
<div select-on-click>
Some text...
<input type="text" ng-model="content" />
</div>

Resources