I am facing problems with two way data binding in angular js. Here is the sample code.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body ng-app="">
<div>
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>
<div id="jack">
</div>
<script>
$("document").ready(function(){
$("#jack").append("<p ng-bind='name'></p>");
});
</script>
</body>
</html>
Over here I am dynamically adding a paragraph with ng-bind to a div called jack using jQuery
For some reason when I type something in input box it is not reflecting in paragraph with ng-bind property.
I am a novice in angular js and would request you to provide me a simple solution to tackle this issue.
You cannot use jQuery to modify DOM outside Angular this way. Angular does not know about that binding as it was not compiled by Angular.
To solve this particular sample, simply remove the jQuery script and change the HTML to this:
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
The example above will work, but I imagine this was not a real-world example. If you post a more specific scenario, I can update my answer to help you solve that.
Edit
Based on your comment, I would create a simple directive to which you could pass your template, it would compile the template and inject the compiled template in the DOM.
Directive:
function myTemplateCompile($compile) {
return {
restrict: 'E',
link: link
}
function link(scope, elem, attrs) {
attrs.$observe('template', (template) => {
elem.html(template);
$compile(elem.contents())(scope);
});
}
}
HTML
<my-template-compile template="any HTML you might need including bindings"></my-template-compile>
You can then change the template attribute of the directive on the fly and it will re-compile and update the DOM based on the new value.
The example above should point you in the right direction. I just have to warn you, that this might be quite dangerous. If the content you are injecting is coming from some user input, this might have very severe security implications. Please make sure you are not exposing your application to attacks.
Well first we need to define the app and create custom directive.
var myApp=angular.module('myApp',[])
.controller('myCtrl',function($scope){
$scope.name="Your name";
})
myApp.directive('myDirective', function() {
return {
restrict: 'E',
template: '<span data-ng-bind="name"></span>'
};
});
After this you need to use above created directive as like below
<my-Directive></my-Directive>
Related
I have two html pages, main.html and nested.html, so the nested.html is actually included in main.html, this way:
main.html starts
<div ng-include src="'nested.html'"></div>
main.html ends
FULL CODE
nested.html
<html>
<h1> I am included, but controller not sending the values to me. </h1>
<input type="text" id="myDatePicker"/>
</html>
main.html
<html ng-controller="MainCtrl">
<h1> I am main.html and controller working properly on me, please take care of my child **given below** </h1>
<div ng-include src="'nested.html'"></div>
</html>
Controller Code:
(function() {
'use strict';
angular.module('bootstrapApp').controller('MainCtrl', MainCtrl);
function MainCtrl($scope, $location, $http, $compile) {
$("#myDatePicker").datepicker({
orientation: 'left'
});
}
});
The Controller code makes the text field a datepicker using jquery. The input field is in nested.html page. If the controller works on the included page, the textfield becomes a datepicker. That's it
Please guide me through how do I apply the same controller MainCtrl to included nested.html page
Thanks.
There are 2 important things to mention here:
The controller scope of the MainCtrl is already applied to the included nested.html. You can review that in the following Plunker: https://embed.plnkr.co/cvILaL3VvnJ5c1YDHDT1/.
You shouldn't use a jQuery datepicker from out of a AngularJS controller. Instead use a datepicker, which is intended for AngularJS (e.g. angular-datepicker)
from what I can guess,you must be using $scope.someVar and you are trying to render it in ng-include. Try creating an obj inside the controller like below:
$scope.obj= {
someVar : 'Value'
};
and use it in ng-include i.e. nested.html as {{obj.someVar}}.
Update 1
As per your new update, try AngularJS datepicker and let me know.
Try to add controller into nested.html file like:
<div ng-controller="MainController">
<h1> I am included, but controller not sending the values to me. </h1>
<input type="text" id="myDatePicker"/>
</div>
And from your comment:
I have a project where I'm currently trying to refactor an old system that was hinged on jquery from the ground up with angular 1.x. However, there are a lot of old HTML forms that I'd like to reuse the bulk of so I don't want to recreate them. I'd love it if there was a way to keep it purely angular, but I'm honestly at a loss of how I'd do that (or whether or not I can). I'm fairly new to angular so there are a lot of inner workings to it that I'm still not privy to.
I've searched around on google and other places including here and I can't really even find other people talking about it. That tells me that either I'm searching badly or it's something that I should probably not be working towards.
All the html pages have identically id'd fields so I feel I can reliably base things on that. For example: all forms with first name text boxes have an id of "cl_fname".
Is there anyway that I can accomplish: getting the form, adding an ng-model="cl_fname" or something to the relevant tag and then display the form? I've gotten to the point where I can get the html page, hold it in the scope and then display using ng-bind-html, but figuring out how to add angular attributes to specific elements I can't figure out.
You can achieve this with jQuery and the attr() method.
I created a plunker here that demonstrates adding angular to an existing "plain" html form.
In the example, I'm using id selectors, but you could use any combination of selectors to ensure you get the right elements.
The below is a quick code snippet from my Plunker example:
HTML:
<div ng-app="myApp">
<form id='myForm1' data-test="test2">
<span>First Name:</span>
<input type="text" id="myForm1_firstName" />
<input type="submit" id="myForm1_Submit" value="Go!" />
</form>
</div>
JS:
// set up angular
var myApp = angular.module('myApp', []);
myApp.controller('MyForm1Controller', ['$scope', function($scope) {
$scope.firstName = 'Angular Working!';
}]);
// use jQuery to add the relevent attributes to our form
var jqMyForm1 = $('form#myForm1');
var jqTxtFirstName = jqMyForm1.find('input[type="text"]#myForm1_firstName');
//add controller to form
jqMyForm1.attr('ng-controller', 'MyForm1Controller');
//bind the textbox to the angular 'firstName' variable
jqTxtFirstName.attr('ng-model', "firstName");
EDIT:
just realised you want to load the html form dynamically.
Version 2 of the plunker (here) will now dynamically load a HTML form from an external resource (separate html page), inject it into the current page, add the angular bindings to it, and then get angular to recognise it.
The key to getting angular to recognise the form is the use of the $compile object (angular $compile documentation).
Again, quick snippets of the code in use:
HTML (main page):
<div ng-app="myApp" ng-controller="LoadingController"></div>
HTML (myForm1.html):
<form id='myForm1' data-test="test2">
<span>First Name:</span>
<input type="text" id="myForm1_firstName" />
<input type="submit" id="myForm1_Submit" value="Go!" />
</form>
JS:
// set up angular
var myApp = angular.module('myApp', []);
// main controller for loading the dynamic form
myApp.controller('LoadingController', ['$scope','$http','$compile', function($scope,$http,$compile) {
$scope.loadHtmlForm = function(formURL) {
$http.get(formURL).then(function successCallback(response){
var jqForm = $(response.data);
var jqTxtFirstName = jqForm.find('input[type="text"]#myForm1_firstName');
//add controller to form
jqForm.attr('ng-controller', 'MyForm1Controller');
//bind the textbox to the angular 'firstName' variable
jqTxtFirstName.attr('ng-model', "firstName");
$('div').append(jqForm);
$compile(jqForm[0])($scope);
});
}
$scope.loadHtmlForm('myForm1.html');
}]);
// form controller for managing the data
myApp.controller('MyForm1Controller', ['$scope', function($scope) {
$scope.firstName = 'Angular Working!';
}]);
What I tried to do the last days is something like that:
%myform(name='somename' ng-controller='whatever')
%myinput(ng-model='user.firstName' ...
controller has a user structure with firstName, lastname, ...
myform should just add some attributes to the <form>-tag, myinput should render a label, the input field and the errors when the somename-form-element is dirty and invalid. Pretty simple stuff.
As easy everything in AngularJS is, I had no chance. Had to move the ng-controller up to an extra div because nothing worked when the controller is defined in the myform tag (ng-click ignored, ...). Ugly but can live with that. No access to the scope in transcluded directives. Can be fixed with the link function and the append. Problem, the whole form validation stuff is not working when this fix is used. So I can have access to the form OR the scope.
What is the correct way to do this in AngularJS? I am really out of ideas and in despair after 4 days of trying and researching (learned the whole AngularJS in less than a day and not a single other problem).
Don't know if it makes sense to post ~ 30 different versions of trying to get this done. Maybe someone can provide a clean solution that is working and following the ideas behind the AngularJS framework (paypal beer thank you included).
Thank you very much in advance!
Anton
scope-fix-solutions:
http://angular-tips.com/blog/2014/03/transclusion-and-scopes/
Issue with transcoded directives: https://github.com/angular/angular.js/issues/5489
... there are thousands of problems about directives and transcoding, seems to be the most ugly part in Angular. Wanted to include more links to solutions I tried, but I am only allowed to post 2.
If somebody needs the solution (small example) - whole example on Plunker - provided by Sander Elias, many thanks!
HTML:
<body ng-controller='AppController as appVm'>
<h1>Hello angular {{appVm.version}}</h1>
<my-form name="test">
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="text" class="form-control" ng-model='appVm.user' required placeholder="Username" name='username' ng-minlength=5>
</div>
<div ng-hide="test.$pristine">
<div ng-show="test.username.$error.required" class="alert alert-danger" role="alert">this is a required field</div>
<div ng-show="test.username.$error.minlength" class="alert alert-danger" role="alert">At least 5 chars</div>
</div>
<button class="btn btn-primary" ng-show='test.$touched || test.$valid'>submit</button>
</my-form>
</body>
JavaScript:
angular.element(document).ready( function() {
// generate module
myModule = angular.module( 'myApp',[]);
// define a simple controller and put the user's name into the scope
myModule.controller('SampleController', ['$scope', function ($scope) {
$scope.user = {
name: 'Hugo'
};
}]);
// make the form directive (just put the two attributes in the form...)
myModule.directive('myform', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<form ng-attr-name="{{name}}" autocomplete="off" novalidate=true>' +
'<fix-transclude></fix-transclude>' +
'</form>',
scope: {
name: '#'
},
link: function (scope, elm, attr, contrl, transclFn) {
scope.$parent[scope.name] = scope[scope.name];
// attach the parent scope (originating one!) to the transcluded content!
transclFn(scope.$parent,function (clone) {
elm.find('fix-transclude').replaceWith(clone);
});
}
}
});
// bootstrap AngularJS
angular.bootstrap(document, ['myApp']);
});
I have a web page with some HTML elements which I cannot edit. I'd like to dynamically attach ng-model attributes to these and have AngularJS re-bind them to the scope. A simplified example of what I want to accomplish can be found here
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script>
function MyCtrl($scope) {
$scope.myModel1 = "Hi";
$scope.myModel2 = "there";
var myModel2 = angular.element("#myModel2");
//This won't work
myModel2.attr("ng-model", "myModel2");
}
</script>
<div ng-app ng-controller="MyCtrl">
<input type="text" ng-model="myModel1"/>
<!-- I can't touch this -->
<input type="text" id="myModel2" />
</div>
You need to use $compile (docs)
$compile(myModel2.attr("ng-model", "myModel2"))($scope);
demo
When you load your page, angular uses $compile on the HTML automatically, that's how it knows which elements to assign which directives to. If you just change the attribute like you tried, angular doesn't know. You have to use $compile.
Using AngularJS if I set a simple input text box value to something like "bob" below. The value does not display if the ng-model attribute is added.
<input type="text"
id="rootFolder"
ng-model="rootFolders"
disabled="disabled"
value="Bob"
size="40"/>
Anyone know of a simple work around to default this input to something and keep the ng-model? I tried to use a ng-bind with the default value but that seems not to work either.
That's desired behavior, you should define the model in the controller, not in the view.
<div ng-controller="Main">
<input type="text" ng-model="rootFolders">
</div>
function Main($scope) {
$scope.rootFolders = 'bob';
}
Vojta described the "Angular way", but if you really need to make this work, #urbanek recently posted a workaround using ng-init:
<input type="text" ng-model="rootFolders" ng-init="rootFolders='Bob'" value="Bob">
https://groups.google.com/d/msg/angular/Hn3eztNHFXw/wk3HyOl9fhcJ
Overriding the input directive does seem to do the job. I made some minor alterations to Dan Hunsaker's code:
Added a check for ngModel before trying to use $parse().assign() on fields without a ngModel attributes.
Corrected the assign() function param order.
app.directive('input', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if (attrs.ngModel && attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
});
The Angular way
The correct Angular way to do this is to write a single page app, AJAX in the form template, then populate it dynamically from the model. The model is not populated from the form by default because the model is the single source of truth. Instead Angular will go the other way and try to populate the form from the model.
If however, you don't have time to start over from scratch
If you have an app written, this might involve some fairly hefty architectural changes. If you're trying to use Angular to enhance an existing form, rather than constructing an entire single page app from scratch, you can pull the value from the form and store it in the scope at link time using a directive. Angular will then bind the value in the scope back to the form and keep it in sync.
Using a directive
You can use a relatively simple directive to pull the value from the form and load it in to the current scope. Here I've defined an initFromForm directive.
var myApp = angular.module("myApp", ['initFromForm']);
angular.module('initFromForm', [])
.directive("initFromForm", function ($parse) {
return {
link: function (scope, element, attrs) {
var attr = attrs.initFromForm || attrs.ngModel || element.attrs('name'),
val = attrs.value;
if (attrs.type === "number") {val = parseInt(val)}
$parse(attr).assign(scope, val);
}
};
});
You can see I've defined a couple of fallbacks to get a model name. You can use this directive in conjunction with the ngModel directive, or bind to something other than $scope if you prefer.
Use it like this:
<input name="test" ng-model="toaster.test" value="hello" init-from-form />
{{toaster.test}}
Note this will also work with textareas, and select dropdowns.
<textarea name="test" ng-model="toaster.test" init-from-form>hello</textarea>
{{toaster.test}}
Update: My original answer involved having the controller contain DOM-aware code, which breaks Angular conventions in favor of HTML. #dmackerman mentioned directives in a comment on my answer, and I completely missed that until just now. With that input, here's the right way to do this without breaking Angular or HTML conventions:
There's also a way to get both - grab the value of the element and use that to update the model in a directive:
<div ng-controller="Main">
<input type="text" id="rootFolder" ng-model="rootFolders" disabled="disabled" value="Bob" size="40" />
</div>
and then:
app.directive('input', ['$parse', function ($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, element, attrs) {
if(attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
}]);
You can of course modify the above directive to do more with the value attribute before setting the model to its value, including using $parse(attrs.value, scope) to treat the value attribute as an Angular expression (though I'd probably use a different [custom] attribute for that, personally, so the standard HTML attributes are consistently treated as constants).
Also, there is a similar question over at Making data templated in available to ng-model which may also be of interest.
If you use AngularJs ngModel directive, remember that the value of value attribute does not bind on ngModel field.You have to init it by yourself and the best way to do it,is
<input type="text"
id="rootFolder"
ng-init="rootFolders = 'Bob'"
ng-model="rootFolders"
disabled="disabled"
value="Bob"
size="40"/>
This is a slight modification to the earlier answers...
There is no need for $parse
angular.directive('input', [function () {
'use strict';
var directiveDefinitionObject = {
restrict: 'E',
require: '?ngModel',
link: function postLink(scope, iElement, iAttrs, ngModelController) {
if (iAttrs.value && ngModelController) {
ngModelController.$setViewValue(iAttrs.value);
}
}
};
return directiveDefinitionObject;
}]);
Hi you can try below methods with initialize of model.
Here you can initialize ng-model of textbox two way
- With use of ng-init
- With use of $scope in js
<!doctype html>
<html >
<head>
<title>Angular js initalize with ng-init and scope</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="app" >
<h3>Initialize value with ng-init</h3>
<!-- Initlialize model values with ng-init -->
<div ng-init="user={fullname:'Bhaskar Bhatt',email:'bhatt.bhaskar88#gmail.com',address:'Ahmedabad'};">
Name : <input type="text" ng-model="user.fullname" /><br/>
Email : <input type="text" ng-model="user.email" /><br/>
Address:<input type="text" ng-model="user.address" /><br/>
</div>
<!-- initialize with js controller scope -->
<h3>Initialize with js controller</h3>
<div ng-controller="alpha">
Age:<input type="text" name="age" ng-model="user.age" /><br/>
Experience : <input type="text" name="experience" ng-model="user.exp" /><br/>
Skills : <input type="text" name="skills" ng-model="user.skills" /><br/>
</div>
</body>
<script type="text/javascript">
angular.module("app",[])
.controller("alpha",function($scope){
$scope.user={};
$scope.user.age=27;
$scope.user.exp="4+ years";
$scope.user.skills="Php,javascript,Jquery,Ajax,Mysql";
});
</script>
</html>
The issue is that you have to set the ng-model to the parent element to where you want to set the ng-value/value .
As mentioned by Angular:
It is mainly used on input[radio] and option elements, so that when the element is selected, the ngModel of that element (or its select parent element) is set to the bound value.
Eg:This is an executed code :
<div class="col-xs-12 select-checkbox" >
<label style="width: 18em;" ng-model="vm.settingsObj.MarketPeers">
<input name="radioClick" type="radio" ng-click="vm.setPeerGrp('market');"
ng-value="vm.settingsObj.MarketPeers"
style="position:absolute;margin-left: 9px;">
<div style="margin-left: 35px;color: #717171e8;border-bottom: 0.5px solid #e2e2e2;padding-bottom: 2%;">Hello World</div>
</label>
</div>
Note: In this above case I alreday had the JSON response to the ng-model and the value, I am just adding another property to the JS object as "MarketPeers". So the model and value may depend according to the need, but I think this process will help, to have both ng-model and value but not having them on the same element.
I had similar issue. I was not able to use value="something" to display and edit.
I had to use the below command inside my <input>along withe ng model being declared.
[(ngModel)]=userDataToPass.pinCode
Where I have the list of data in the object userDataToPass and the item that I need to display and edit is pinCode.
For the same , I referred to this YouTube video