How to can I define scope to HTML block in Angular? - javascript

I have a very large form in my application page, and I have a JSON variable, where I saving all form data in it, and I'm using controllerAs expression.
<form>
<input type="text" data-ng-model="ctrl.myJSON.name"/>
<input type="text" data-ng-model="ctrl.myJSON.old"/>
<input type="text" data-ng-model="ctrl.myJSON.address"/>
<input type="text" data-ng-model="ctrl.myJSON.email"/>
<input type="text" data-ng-model="ctrl.myJSON.phone"/>
<!-- and many more... -->
</form>
How to can I define myJSON as the form scope, for no need repeat this variable many time in all fields?

you can use angular extend to copy the json data to $scope. And then, you can use directly:
.controller('YourController', function($scope) {
$scope.readData = function() {
// replace with your read data function
var myJSON = { name: 'test' };
angular.extend($scope, myJSON);
}
}
after that, the variables will work directly:
<input type="text" data-ng-model="name"/>

Wrap the form inside a separate, dedicated controller FormController and copy the myJson key-value-pairs to its $scope.
This is possible in the later versions of Angular using scope inheritance/nested scopes.
HTML
<div ng-controller="MainController">
<form ng-controller="FormController">
<input type="text" data-ng-model="name"/>
<input type="text" data-ng-model="old"/>
<input type="text" data-ng-model="address"/>
<input type="text" data-ng-model="email"/>
<input type="text" data-ng-model="phone"/>
<!-- and many more... -->
</form>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('MainController', ['$scope', function($scope) {
// other logic goes here
}]);
myApp.controller('FormController', ['$scope', function($scope) {
// Initialize myJson by loading its data from a service
angular.extend($scope, myJson);
}]);
JSFiddle: https://jsfiddle.net/206redxb/5

Related

Publishing an Input outside the Form to the Form via name programmatically with Angularjs

I need to publish an Input to a Form, while the Input sits outside the form. I managed to add the input, but the result is not what I excactly need (see the console output)
So I basically adding the outer input element to the form via form.$addControl(outerInput)
const MyApp = angular.module('app', []);
MyApp.controller('formCtrl', ['$scope', '$element', function($scope, $element){
$scope.dataModel = {
name: 'robert arschfick',
email: 'blabla',
age: 25,
text: 'text'
};
$scope.addOuterInputToForm = function(form, inputID){
// annoying as hell, I am retrieving the input element;
var input = angular.element(document.getElementById(inputID))[0];
form.$addControl(input);
console.log(form);
};
}]);
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app" ng-controller="formCtrl">
<form ng-submit="" name="testForm">
<input type="name" ng-model="dataModel.name" name="name" required>
<input type="email" ng-model="dataModel.email" name="email" required>
<input type="number" ng-model="dataModel.age">
</form>
<!-- I need to add this input the same way the inner inputs name
and email are published to the form, so that it is addressable
via its name in the form and that it is part of the form.controls
-->
<input type="text" required id="inputToAdd" name="text"
ng-model="dataModel.text">
<button ng-click="addOuterInputToForm(testForm, 'inputToAdd')">
Add Control
</button>
</div>
The input is added as a control, but the object looks different and has not all the ng $validators on it. Also I need to add it by name as a property to the form like "email" and "name" are:
This is the outside input added to the form. It misses all the ng-form attributes see the image after
This is the inside email input added to the form somehow internally. It has all the ng form properties like $untouched, $prestine etc.
So what I need is now to somehow fake this internal adding of the outer input programmatically so that the outer input is contained the same way by the form as the inner inputs "email" and "name"
Sorry for my english skills and I hope I was clear enough. Thanks in advance :)
The $addControl method needs the ngModelController of the <input>, not the <input> element itself.
To get the ngModelController of the element, enclose it in a div that has an ng-form directive:
<div ng-form="other">
<input type="text" required id="inputToAdd" name="text"
ng-model="dataModel.text">
</div>
<button ng-click="testForm.$addControl(other.text)">
Add Control
</button>
The DEMO
const MyApp = angular.module('app', []);
MyApp.controller('formCtrl', ['$scope', '$element', function($scope, $element){
$scope.dataModel = {
name: 'robert arschfick',
email: 'blabla',
age: 25,
text: 'text'
};
}]);
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app" ng-controller="formCtrl">
<form ng-submit="" name="testForm">
<input type="name" ng-model="dataModel.name" name="name" required>
<input type="email" ng-model="dataModel.email" name="email" required>
<input type="number" ng-model="dataModel.age">
</form>
<!-- I need to add this input the same way the inner inputs name
and email are published to the form, so that it is addressable
via its name in the form and that it is part of the form.controls
-->
<div ng-form="other">
<input type="text" required id="inputToAdd" name="text"
ng-model="dataModel.text">
</div>
<button ng-click="testForm.$addControl(other.text)">
Add Control
</button>
</div>

Get value of angular to localStorage

I want to get the value of angular and store it in my local storage. something like this:
<input type="text" id="ID" value="{{sudent.id}}">
<script>
localStorage.setItem("STUDID", document.getElementById("ID").value);
</script>
and I want the result to be:
<script>
localStorage.setItem("STUDID", "HUMMS-201906");
</script>
use ng-model so as to provide two-way data binding and in controller access the ng-model value using $scope.
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.student = {
"id": 101
};
console.log($scope.student.id);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-app="inputExample">
<div ng-controller="ExampleController">
<input type="text" name="studentId" ng-model="student.id" required>
</div>
</body>

Retrieving the value of ng-model from Directives template to Another Html file

I can't retrieve the ng-model value of my template-url from my name directive.
team-two.html
<form name="userForm" novalidate>
<div name-directive></div>
</form>
<pre>{{userForm.firstname}}</pre>
here i have name-directive inside the form and a pre tag to view as I type a value in input text of name-directive
name-directive.js
(function () {
'use strict';
var app = angular.module('app.input-form');
app.directive('nameDirective', function () {
return {
restrict: 'AE',
scope: true,
controller: function() {
var vm = this;
vm.namePattern = /^[a-zA-Z ]{1,25}$/;
},
controllerAs: 'vm',
templateUrl: '/src/client/app/input-form/name.html'
}
});
})();
in here, I have a templateUrl dont mind the other codes coz I think it not related to my concern.
name.html
<input type="text" name="firstname" class="form-control" placeholder="Enter
your first name"
ng-model="firstname"
ng-minlength="2"
ng-maxlength="20"
required
ng-pattern="vm.namePattern"/>
in here, I have a ng-model that I want to access which is the firstname..
Edit Note: I discovered that if I add $viewValue in <pre>{{userForm.firstname.$viewValue}}</pre> it works.. I get what I want.. But I think that it is not the exact solution for my problem..
Edit 2 Added link to Plunker: https://plnkr.co/edit/6glStzEq5ckZZzph2qLw?p=preview
Since you use the controllerAs in the directive need to reference that when you are accessing variables from the html.
ng-model="vm.firstname"
<input type="text" name="firstname" class="form-control" placeholder="Enter
your first name"
ng-model="vm.firstname"
ng-minlength="2"
ng-maxlength="20"
required
ng-pattern="vm.namePattern"/>

Resolving ng-model outside the form

I have an html file with 2 form elements with input elements inside both. I would be using the ng-if to select which form element I need. The input elements are bound to the same model. But I am unable to resolve it outside the form scope.
<form ng-if="some_name == '1'">
<input ng-model="model_name">
</form>
<form ng-if="some_name == '2'">
<input ng-model="model_name">
</form>
{{model_name}} //This is different from the value of either of the input elements
//it has the initial value which i would assign : $model_name = "xyz"; in my associated js file
The reason you are not able to see those changes outside your form is because you are using 'ngIf' directive to add/remove the DOM and also the 'ngIf' directive creates a new scope.
There are two quick ways to solve this:
1) Make use of 'ngShow'. Look at the below example:
angular.module('app', [])
.controller('HomeController', function($scope) {
$scope.model_name = 'Hi';
$scope.some_name = '1';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="app" data-ng-controller="HomeController">
<form ng-show="some_name == '1'">
<input ng-model="model_name">
</form>
<form ng-show="some_name == '2'">
<input ng-model="model_name">
</form>
{{model_name}}
</div>
2) Make the input model an object, instead of a primitive.
angular.module('app', [])
.controller('HomeController', function($scope) {
$scope.model_name = {
value: 'Hi'
};
$scope.some_name = '1';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="app" data-ng-controller="HomeController">
<form ng-if="some_name == '1'">
<input ng-model="model_name.value">
</form>
<form ng-if="some_name == '2'">
<input ng-model="model_name.value">
</form>
{{model_name.value}}
</div>

Two-way data binding is not working on text boxes in AngularJS

I tried to implement two-way data binding in two text boxes using AngularJS, however it is not working.
Here is my code:
<html ng-app="myApp">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script>
var app = angular.module('myApp', []);
</script>
</head>
<body ng-controller="tasksController">
<input type="text" ng-model="username" value="{{userage}}">
<input type="text" ng-model="userage" value="{{username}}">
</body>
Can anyone help me on this?
You haven't defined tasksController in your Angular code:
<script>
var app = angular.module('myApp', []);
app.controller('tasksController', function($scope){
$scope.username = "John Doe";
$scope.userage = 45;
});
</script>
The model scope will then work. Also, you don't need to bind the model to the input value. ng-model binds the value automatically :
<input type="text" ng-model="username">
<input type="text" ng-model="userage">

Categories

Resources