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.
Related
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>
I am building a drum machine using AngularJS and having issues adjusting the tempo from the user interface.
I have got the object "this.tempo=120" & "<input class="bpm-input" type="number" onchange="updateBPM()" min="100" max="150" ng-model="$ctrl.tempo"></input>"
This doesn't seem to update the tempo value, only the value shown in the input box.
What function would I need to update the value within the controller?
It is normal, when you use AngularJS, you need to use the Angular WAY.
In other words, what angular do for you is the only way to do it.
AngularJS drastically control your DOM and use it as a copy.
If you change the DOM without the angular behavior, angular cannot update his copy and throws bad behaviors.
You need to use all Angular things, to tell him to apply his magic on your DOM.
Change your onclick attribute by ng-click angular directive, put your updateBPM into your controller scope, and this will works.
Hope that helps you!
Basic things you can do are as in the attached snippet also try having Angular patterns for a manageable code base and good performance Patterns
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myController as myCtrl">
<input class="bpm-input" type="number" ng-change="myCtrl.updateBPM()" min="100" max="150" ng-model="myCtrl.tempo"></input>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
var myCtrl = this;
myCtrl.tempo=120;
myCtrl.updateBPM = function(){
alert(myCtrl.tempo);
}
});
</script>
</body>
</html>
Code is attached below
<script>
var mainModule = angular.module('mainModule', [])
.controller('mainCntrl', function($scope) {
var vm = this;
vm.tempo = 120;
});
</script>
<div ng-app="mainModule">
<div ng-controller="mainCntrl as ctrl">
<input class="bpm-input" type="number" min="100" max="150" ng-model="ctrl.tempo"></input>
</div>
</div>
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!';
}]);
I am learning Angular JS and I am stuck at a pretty basic step.
Here is my test code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
function enable()
{
$("#test_model").attr("data-ng-model", "test");
$("#test_bind").attr("data-ng-bind", "test");
};
</script>
</head>
<body>
<div data-ng-app="">
<div>
<input type=text id=test_model />
</div>
<div>
<p id=test_bind></p>
</div>
<button onclick=enable()>Enable</button>
</div>
</body>
</html>
Here, what I expect to happen is, when the Enable button is clicked, it should enable the bind, and so if anything is typed into the #test_model input, it should update #test_bind paragraph. But it is not working.
I can see with Firebug that the attributes (data-ng-model and data-ng-bind) are being updated when the Enable button is clicked, but it is not taking effect as it would if it were statically coded (hard-coding the model and bind parameters).
If I code it statically, then I notice that 3 new classes (ng-pristine, ng-untouched and ng-valid) are automatically added to #test_model and one new class (ng-binding) is added to #test_bind. So I changed my enable() function to this:
function enable()
{
$("#test_model").attr("data-ng-model", "test");
$("#test_bind").attr("data-ng-bind", "test");
$("#test_model").addClass("ng-pristine");
$("#test_model").addClass("ng-untouched");
$("#test_model").addClass("ng-valid");
$("#test_bind").addClass("ng-binding");
};
But still, not working.
What am I missing?
If you want to dynamically add Angular directives like ng-model, ng-bind etc.
you must create your own directive and use $compile.
You can use angular ng-show or ng-switch to switch showing DOM elements without bindings and elements with ng-model and other attributes that you need.
Below is my angularjs code,
When I try to enter any text in the textbox, it doesn't appear in the binding.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/angular.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('cont', ['$scope', function($scope) {
}]);
</script>
</head>
<body ng-app="myApp">
<input type="text" ng-bind="user"></input>
<p>{{user}}</p>
</body>
</html>
You would need to use ng-model directive for 2-way binding. ng-bind is just one-way which updates the bound element with data (model value) when a digest cycle happens. Without ng-model when you update the textbox there wont be any digest cycle. Angular has directive definition for types like input and other form controls which requires optional ng-model directive. And these element directives registers events like change/input etc only if it gets the optional ng-model controller on the target element. And when you have them it uses ng-model controller to set the view-value, model-value and triggers the digest cycle when that event occurs. Of course with the new angular versions there is an ng-model-options which you can set at the element level or at a global level to specify when do you want the model value update (and form validation) to happen.
So do:-
<input type="text" ng-model="user" name="user"></input>
<p>{{user}}</p>
Though not an issue in your case, you are missing the usage of ng-controller="cont". Without it all properties will be attached to the rootScope in your case. So may be:
<body ng-app="myApp">
<div ng-controller="cont">
<input type="text" ng-model="user" name="user"></input>
<p>{{user}}</p>
</div>
</body>