I first initialize my app with ng-app="myApp" in the body tag and this works fine for all angularized-html that is loaded on first page load.
Later on I have some code that loads angularized-html in to the DOM.
In angular 1.08 I could just run angular.bootstrap($newLoadHTML, ["myApp"]) after the load and it would work; where $newLoadHTML is the newly added HTML grabbed with jQuery.
In angular 1.2 this does no longer work:(
Error: [ng:btstrpd] App Already Bootstrapped with this Element '' http://errors.angularjs.org/1.2.0-rc.2/ng/btstrpd?p0=%3Cdiv%20ng-controller%3D%22AfterCtrl%22%3E
I am getting this error which I understand, but I don't know how to solve it.
What I need to be able to do is load angularized-html and then make angular aware of it.
Here is a plunker to illustrate it: http://plnkr.co/edit/AHMkqEO4T6LxJvjuiMeT?p=preview
I will echo what others have mentioned: this kind of thing is generally a bad idea, but I also understand that you sometimes have to work with legacy code in ways you'd prefer not to. All that said, you can turn HTML loaded from outside Angular into Angular-bound views with the $compile service. Here's how you might rewrite your current example to make it work with $compile:
// We have to set up controllers ahead of time.
myApp.controller('AfterCtrl', function($scope) {
$scope.loaded = 'Is now loaded';
});
//loads html and afterwards creates a controller
$('button').on('click', function() {
$.get('ajax.html', function(data) {
// Get the $compile service from the app's injector
var injector = $('[ng-app]').injector();
var $compile = injector.get('$compile');
// Compile the HTML into a linking function...
var linkFn = $compile(data);
// ...and link it to the scope we're interested in.
// Here we'll use the $rootScope.
var $rootScope = injector.get('$rootScope');
var elem = linkFn($rootScope);
$('.content').append(elem);
// Now that the content has been compiled, linked,
// and added to the DOM, we must trigger a digest cycle
// on the scope we used in order to update bindings.
$rootScope.$digest();
}, 'html');
});
Here is an example: http://plnkr.co/edit/mfuyRJFfA2CjIQBW4ikB?p=preview
It simplifies things a bit if you can build your functionality as a directive instead of using raw jQuery--you can inject the $compile and $rootScope services into it, or even use the local scope inside the directive. Even better if you can use dynamic binding into an <ng-include> element instead.
Your approach doesn't seem right. You are usinging jQuery and Angular together in an inappropriate way that is likely to have conflicts.
Angular's built in template support is the best way to do this either using ng-include or you can use Angular's routing and along with ng-view. The documentation is here:
http://docs.angularjs.org/api/ng.directive:ngInclude
http://docs.angularjs.org/api/ngRoute.directive:ngView
The simplest possible thing would be to just set the ng-include to the url string:
<div ng-include="'ajax.html'"></div>
If you actually need it to load dynamically when you do something then this is a more complete solution for you:
http://plnkr.co/edit/a9DVEQArS4yzirEQAK8c?p=preview
HTML:
<div ng-controller="InitCtrl">
<p>{{ started }}</p>
<button ng-click="loadTemplate()">Load</button>
<div class="content" ng-include="template"></div>
</div>
Javascript:
var myApp = angular.module('myApp', [])
.controller('InitCtrl', function($scope)
{
$scope.started = 'App is started';
$scope.loadTemplate = function() {
console.log('loading');
$scope.template = "ajax.html";
}
}).controller('AfterCtrl', function($scope)
{
$scope.loaded = 'Is now loaded';
});
Loading an AngularJS controller dynamically
The answer to this question fixed my problem. Since I need to create the controllers after the content was added to the DOM. This fix requires me too register controllers after I have declared it. If someone has an easier solution pleace chip in.
One other gotcha that leads to this Bootstrapping error is the nginclude or ngview scenarios where your dynamic html includes script references to angular js.
My html below was causing this issue when it got injected into an existing Angular page. The reference to the angular.min.js caused Angular to rebootstrap:
<div id="fuelux-wizard" class="row-fluid" data-target="#step-container">
<ul class="wizard-steps">
<li data-target="#step1">
<span class="step">1</span>
<span class="title">Submit</span>
</li>
<li data-target="#step2">
<span class="step">2</span>
<span class="title">Approve</span>
</li>
<li data-target="#step3">
<span class="step">3</span>
<span class="title">Complete</span>
</li>
</ul>
</div>
<script src="/Scripts/Angular/angular.min.js"></script>
<script type="text/javascript">
angular.element('#requestMaster').scope().styleDisplayURL();
</script>
Related
First of all, I'm new in Angularjs and not good at English.
I tried to add <li> by using directive, and below link is completed result of my first purpose.
Add element using directive
Second is passing value from Controller to directive or from directive to Controller, known as two-way binding.
But in this step, I couldn't figure out how to use #,= and '&'.
I guessed it's because of using directive in directive.
In my original code, my modal is made of directive, so button directive seems cannot get value from Controller.
I'm sorry I cannot show you my own code because I don't know how to make many directives in fiddle.
.
.
I wanna know there are any way to add element dynamically without using directive.
No matter what you suggested like link, doc, or something, it'll be great helpful to me.
Just give a little attention please. Thank you. Have a nice day!
This may helpful.
You can use javascript as follows for achieving this.
https://jsfiddle.net/u08pa50z/
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
var el = document.createElement("ul");
el.style.width="600px";
el.style.height="500px";
el.style.background="green";
var parent=document.getElementById("sib");
parent.appendChild(el);
$scope.myFunc = function() {
var ch = document.createElement("li");
el.appendChild(ch);
};
}]);
You can go with ng-include
Fetches, compiles and includes an external HTML fragment.
I have an traditional asp.net application which reads HTML template and renders it inside div control. Using bootstrap xeditable user can edit certain parts of the template (only text). This template is later used to send emails. This functionality is working fine. Now I am rewriting this application using AngularJs and WebApi. I am using angular route to route to different pages (plain html) of the application. I am able to load the template using directive. now I want to allow user to edit the text and save the complete template so that it can be used later for sending email.
MyTemplate.html
<p>this is some text</p>
<p>this is some more text</p>
<p>this is some another text</p>
Directive
myapp.directive("customDirective", function () {
return {
templateUrl: 'MyTemplate.html'
};
});
Notify.html
<div>
<h2>{{message}}</h2>
<input type="button" ng-click="Redirect()" value="Report" />
</div>
<custom-directive></custom-directive>
I want that user should be able to edit the text in MyTemplate.html and save it as complete template for later use. Is this achievable?
Do not store it in file. Store the template in your database. Provide a default value there, so something shows if the user has not modified it yet.
In you directive, load the template from your database through your API. After you do that, append the template to the contents of your directive inside your link callback function and compile the directive (if needed).
myapp.directive("customDirective", ($compile, yourService) => {
return {
link: (scope, elem) => {
yourService.fetchTemplate().then(template => {
elem.html(template);
$compile(elem.contents())(scope);
});
}
}
});
Please make sure to sanitise your data properly. It could be fairly dangerous injecting and compiling template created by the user.
I hope this points you in the right direction.
Edit
You might not event need the $compile step. It depends on what kind of template you have in mind. If it is just a simple element without any connection to angular, simply skip the $compile line.
Edit 2 - Display the template on click
Please note the following is just a very simplified version, but it should point you in the right direction.
In your parent controller
$scope.state = {
displayTemplate: false
};
In your template
<my-template-directive ng-if="state.displayTemplate"></my-template-directive>
<button ng-click="state.displayTemplate = true">Show Template</button>
Using Polymer 1.0, I set up an iron-form to submit a simple contact form. The idea is to submit the form to a database table using PHP and then display a response from the PHP side into the browser without refreshing - typical AJAX. I'm getting hung up on the Polymer environment though - it seems like there should be a correct way to do this, but hours of searching and tinkering hasn't been fruitful.
I did start this project using the Polymer Starter Kit (lite), which uses a script (app.js) to add event listeners and such. So far I haven't broken that functionality, though all of the examples in documentation do NOT do it this way, so it makes things a little more complicated since I'm still getting used to Polymer in general.
Here's what I've got so far. Thanks so much for any advice you can offer.
index.html
<!-- this is where the output should be displayed -->
<div id="output"></div>
<!-- this is the web form -->
<form is="iron-form" id="contactus-form" method="post" action="/">
<input type="hidden" name="action" value="contactus-form">
<paper-input id="contactus-field-Name" name="Name" label="Name" value="test"></paper-input>
<paper-button onclick="submitHandler(event)">Send</paper-button>
</form>
...
<script src="script/app.js"></script>
<script>
function submitHandler(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
</script>
app.js
(function(document) {
'use strict';
addEventListener('iron-form-submit', function(e) {
// this works and displays the POSTed values in the browser
document.querySelector('#output').innerHTML = JSON.stringify(e.detail);
// I'm looking for a way to first submit this data through PHP and
// display the output of that process in the #output div rather than the
// raw form input itself.
}
})(document);
FAILED METHOD 1
I tried adding an iron-ajax element into index.html and referencing it from app.js as shown below. Unfortunately, when it tries to add the event listener, the entire app crashes. It seems strange because there are many other pieces in app.js which add event listeners in the same way.
index.html
<iron-ajax id="contactus-output" url="/form/contact.php" params="" handle-as="json"></iron-ajax>
<!-- same form as before goes here -->
app.js
var coutput = document.querySelector('#contactus-output');
coutput.addEventListener('response', function() {
// nothing fancy here yet, just trying to see if I can do this
document.querySelector('#output').innerHTML = 'hello world';
}
FAILED METHOD 2
I found This Answer on SO and decided to try the iron-form-response event. The output I receive now is [object HTMLElement], which is at least something, although I'm not sure if it is actually working or not.
Everything else staying the same, I changed the target of my form to point to my php script and then replaced what I had in app.js with the following:
app.js
addEventListener('iron-form-response', function(e) {
document.querySelector('#output').innerHTML = e.detail;
});
Am I getting any closer?
NOT GIVING UP
Using my second failed method above, the iron-form appears to be making a request, because when I listen for the 'iron-form-response' event, it does fire.
However, the only thing that gets returned is [object HTMLElement] - no idea what to do with that. I tried spitting out some of its properties (as documented on developer.mozilla.org - .title, .properties, .style, etc) but they appear to be empty. Does iron-form really return an HTMLElement object or is this a mistake? I had figured it would return the results from the PHP script I'm submitting the form to just like a normal XMLHttpRequest. If iron-form somehow compresses this into an object, is there a way to pull it out again?
TL;DR
I think what this entire thing boils down to is this: HOW can I properly add an Event Listener (for iron-form-request) when my iron-form is in index.html and index.html is bootstrapped by app.js as happens by default in the Polymer 1.0 Starter Kit?
Further Simplified: How do I add event listeners properly to Polymer's shadow DOM when I'm NOT creating an element (just using it)?
BUG?
With the help of user2422321's wonderful answer below, the iron-request is being performed and a successful iron-request response is received. However, its "response" property returns NULL even though "succeeded" returns true, there were no errors, and the XHR resolved completely. Both "get" and "post" methods were tested with the same NULL result.
I see that there was a bug which matches these symptoms precisely logged in GitHub 10 days ago, though it hasn't seen much attention: Issue 83. This is unfortunate, but it appears to be a bug. I'm not convinced there will be any way to get this working until the element itself is repaired.
WHAT DOES IRON-REQUEST WANT TO SEE?!
As I explore this further, I see that even the XHR directly is returning "null" even though it has the responseURL correct and a statusText of "OK". I'm beginning to wonder if the actual PHP script I'm trying to run - which currently just outputs "Hello World" - is at fault.
Does iron-form-request expect a certain format or data type in the results? I tried adding header('Content-Type: text/plain'); to my PHP file, then I tried formatting it as a verified JSON string, but response is still null. Seems that nothing works.
Old school direct XMLHttpRequests work normally... is iron-form malforming something before the request even gets submitted?
I did set up a handler to catch iron-form-error but none are received. According to every single piece of information in the response, everything is perfect in the world. Just... null response. Over and over and over again... this is so incredibly frustrating.
SOLUTION! (sort of)
Okay, I got desperate enough that I started thumbing through the iron source code itself. It appears that iron-form is still somewhat glitchy at the moment and only returns content if the response is properly formatted json. In iron-request.html, it appears to allow the following types, but don't be fooled. I could only get json to work - I assume the rest will eventually fall into line.
json (application/json)
text (text/plain)
html (text/html)
xml (application/xml)
arraybuffer (application/octet-stream)
Therefore, for the time being, we need to format our response as JSON and include a DOCTYPE declaration to match.
In my case, this looks like so (thanks goes out to user2422321 for helping me so much):
index.php
<div id="output">{{myOutput}}</div>
<form is="iron-form" id="contactUsForm" method="get" action="/contactus.php" on-iron-form-response="_onResponseRetrieved">
<paper-input id="Name" name="Name" value="text" label="Name"></paper-input>
<paper-button id="contactSubmitButton" on-tap="_submitHandler">Submit</paper-button>
</form>
app.js
(function(document) {
...
app._onResponseRetrieved = function(e) {
this.myOutput = e.detail;
console.log(e);
};
app._submitHandler = function(e) {
this.$.contactUsForm.submit();
});
...
})(document);
Then finally, and this was the important last piece of the puzzle. I hadn't previously considered that the contents this file outputs would be very important since straight up XMLHttpRequests return whatever the file spits out.
contactus.php
<?php
// This is the line I added
header('Content-Type: application/json');
// Actual Code goes here
// Then make sure to wrap your final output in JSON
echo '{"test":"this is some test json to try"}';
With all those pieces in place, it works and e.detail.response contains the JSON response we echoed from contactus.php.
Not quite sure I understand what is it that doesn't work, but this is how I think it should be done "pure" Polymer way (by that I mean as little Javascript as possible).
<div id="output">{{myOutput}}</div>
<!-- this is the web form -->
<form is="iron-form" id="contactUsForm" method="post" action="/" on-iron-form-response="_onResponseRetrieved">
<input type="hidden" name="action" value="contactUsForm">
<paper-input id="contactus-field-Name" name="Name" label="Name" value="test"></paper-input>
<paper-button on-tap="_submitHandler">Send</paper-button>
</form>
_onResponseRetrieved: function(e)
{
//I'm not 100% sure what e.detail actually contain, but the value your looking for should be inside there somewhere
this.myOutput = e.detail;
}
_submitHandler: function(e)
{
//Note that I renamed the id of your form :)
this.$.contactUsForm.submit();
}
I've also seen recommendation that onclick should be on-tap so that it works properly on mobile devices, therefore I changed it.
The UI should now update as soon as you receive a response from the server!
-
EDIT:
Because you are using Polymer Starter Kit which is doing some of main logics inside the index.html some things are a bit different. In the Polymer documentation one is usually given examples where they show some piece of code inside an element, while the index.html does not look or function exactly as an element, which indeed can be confusing. In my own project I actually skipped all logics inside the index.html because I thought it seemed messy and complicated, but when looking back it's not all that weird (still not pretty in my opinion). I'm not sure about this, but the way index.html is setup might be the way to setup custom-elements if you want to separate the code (javascript) and the look (html/css).
So to get your code working:
In app.js you see this line:
var app = document.querySelector('#app');
You can think of the app variable as a custom-element.
In index.html you can see this line, which kinda says: "if you click on me I will call the method onDataRouteClick in the element app":
<a data-route="home" href="/" on-click="onDataRouteClick">
So, why will it call the method on the element app? That's because the line above is a child of: <template is="dom-bind" id="app"> (note the id has nothing to do with this, other than that we located it in Javascript by that id, so when I talk about the app object I'm talking about the one in Javascript).
Inside app.js we can then define what will happen when onDataRouteClick is called by doing the following:
app.onDataRouteClick = function() {
var drawerPanel = document.querySelector('#paperDrawerPanel');
if (drawerPanel.narrow) {
drawerPanel.closeDrawer();
}
};
I don't know why, but they keep using this line to find objects:
var drawerPanel = document.querySelector('#paperDrawerPanel');
But when you are in the scope of app you can actually use this instead, which I think is more Polymerish:
var drawerPanel = this.$.paperDrawerPanel;
-
Sorry if you knew all this already, now how do we get your code working?
Inside app.js you add this:
app._onResponseRetrieved = function(e)
{
//I'm not 100% sure what e.detail actually contain, but the value your looking for should be inside there somewhere
this.myOutput = e.detail;
console.log(e); //Check the console to see exactly where the data is
};
app._submitHandler = function(e)
{
//Note that I renamed the id of your form :)
//We are in the scope of 'app' therefore we can write this
this.$.contactUsForm.submit();
};
And in index.html you would have something similar to this (obviously it should be within the template element):
<div id="output">{{myOutput}}</div>
<!-- this is the web form -->
<form is="iron-form" id="contactUsForm" method="post" action="/" on-iron-form-response="_onResponseRetrieved">
<input type="hidden" name="action" value="contactUsForm">
<paper-input id="contactus-field-Name" name="Name" label="Name" value="test"></paper-input>
<paper-button on-tap="_submitHandler">Send</paper-button>
</form>
I am using Polymer 2 and I had a similar problem like this.
Here is my element file :
<template is="dom-bind">
<iron-ajax
auto
id="ajax"
url="test.php"
handle-as="json"
method="POST"
body='{"email":"ankita#gmail.com", "lastlogin":"Feb 21st 2016", "notifications":6}'
content-type = "application/json"
last-response="{{responseObject}}" >
</iron-ajax>
<login-element details="[[responseObject]]"></login-element>
</template>
And the login-element.html looks like this:
<dom-module id="login-element" >
<template>
<!--<form action="test1.php" method="post" enctype='application/json'>-->
<!--Name: <input type="text" name="name"><br>-->
<!--E-mail: <input type="text" name="email"><br>-->
<!--<input type="submit" onclick="submitForm()">-->
<!--</form>-->
<h2>{{details.email}}</h2>
</template>
<script>
Polymer({
is:"login-element",
properties:{
details:Object
}
});
</script>
And test.php
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo json_encode($data);
exit;
I'm starting to learn angularJS better, and I've noticed that AngularJS tries to make strong emphasis on separating the view from the controller and encapsulation. One example of this is people telling me DOM manipulation should go in directives. I kinda got the hang of it now, and how using link functions that inject the current element allow for great behavior functionality, but this doesn't explain a problem I always encounter.
Example:
I have a sidebar I want to open by clicking a button. There is no way to do this in button's directive link function without using a hard-coded javascript/jquery selector to grab the sidebar, something I've seen very frowned upon in angularJS (hard-coding dom selectors) since it breaks separation of concerns. I guess one way of getting around this is making each element I wish to manipulate an attribute directive and on it's link function, saving a reference it's element property into a dom-factory so that whenever a directive needs to access an element other than itself, it can call the dom-factory which returns the element, even if it knows nothing where it came from. But is this the "Angular way"?
I say this because in my current project I'm using hard-coded selectors which are already a pain to mantain because I'm constantly changing my css. There must be a better way to access multiple DOM elements. Any ideas?
There are a number of ways to approach this.
One approach, is to create a create a sidebar directive that responds to "well-defined" broadcasted messages to open/close the sidebar.
.directive("sidebar", function(){
return {
templateUrl: "sidebar.template.html",
link: function(scope, element){
scope.$root.$on("openSidebar", function(){
// whatever you do to actually show the sidebar DOM content
// e.x. element.show();
});
}
}
});
Then, a button could invoke a function in some controller to open a sidebar:
$scope.openSidebar = function(){
$scope.$root.$emit("openSidebar");
}
Another approach is to use a $sidebar service - this is somewhat similar to how $modal works in angularui-bootstrap, but could be more simplified.
Well, if you have a directive on a button and the element you need is outside the directive, you could pass the class of the element you need to toggle as an attribute
<button my-directive data-toggle-class="sidebar">open</button>
Then in your directive
App.directive('myDirective', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
angular.element('.' + attrs.toggleClass).toggleClass('active');
}
};
}
You won't always have the link element argument match up with what you need to manipulate unfortunately. There are many "angular ways" to solve this though.
You could even do something like:
<div ng-init="isOpen = false" class="sidebar" ng-class="{'active': isOpen}" ng-click="isOpen = !isOpen">
...
</div>
The best way for directive to communicate with each other is through events. It also keeps with the separation of concerns. Your button could $broadcast on the $rootScope so that all scopes hear it. You would emit and event such as sidebar.open. Then the sidebar directive would listen for that event and act upon it.
There may be a better way of doing this, but currently I have an nicely encapsulated, JavaScript object which can have some configurable options. I include a chunk of HTML code on a page (via Dreamweaver 'snippets'), and on page load my JS file runs through the DOM and identifies any of those code chunks as a particular functionality, and goes ahead and sets that functionality up.
That's all fine up until I wish to add more than one object on a page, and have them be configurable. The important point here is that you can add as many of these objects onto a page as you like with my current setup - because they're generic at that point, and have no 'id' attribute.
Now I wish to configure these objects, so I thought, "How about an external file containing the config settings, which these objects check for and apply if a config object is found". This works fine too, but the config data feels a bit 'removed' now. I imagine this will be annoying for my other colleagues eventually, it's just another Thing To Remember.
So to my question, I'm happy to insert these code blocks which will still trigger self-instantiating objects on page load - but what I'd like to try is also inserting a script block which contains the config settings. I need a means of that inserted code block knowing that its parent element is the context for configuration.
Example code:
<div class="snippet">
<_contents of this 'snippet'_/>
<script type="text/javascript">
new Snippet().init({
rootElement: REFERENCE_TO_THIS_SCRIPT_TAGS_PARENT_NODE,
configOptionA: true,
configOptionB: false
});
</script>
</div>
Note: The <div class="snippet"> has no 'id' attribute on purpose, because I want to allow for more than one of these to be dropped onto a page.
Other solutions welcome, so long as they adhere to my few restrictions!
My other related question (now answered) addresses this now, essentially I ended up with:
<div class="snippet">
<elements... />
<script type="text/javascript">
var tmpVarName = 'configOb_'+Math.floor(Math.random()*1111111) ;
document[tmpVarName] = {
remainVisible:true,
hoverBehaviour:false
};
</script>
</div>
...and then in a script loaded on every page, which scans for any appropriate elements to instantiate and config:
var snippets = yd.getElementsBy(function(el){
return yd.hasClass(el, "snippet");
},null,document );
for( var i=0; i<snippets.length;i++ )
{
var s = snippets[i] ;
yd.generateId(s, '_snippet_'+i );
var tag = yd.getElementBy(function(el){
return true;
},'script',s );
var ob = new Snippet();
ob.setId( s.id );
ob.init( eval( tag.innerHTML ) );
}
For a more complete context of the above code;
yd = YAHOO.util.Dom
Snippet.init() and Snippet.setId() are exposed methods on a Module object called Snippet()
Now that my inserted 'chunks' of content have no id attribute, and dynamically evaluated, contextual config objects - I am free to add as many variants as I like. My only real concern is performance if a whole bunch of these Snippet() objects are added to my page (not likely).