AngularJS: how to know when the $compile has finished? - javascript

http://plnkr.co/edit/GRVZl35D1cuWz1kzXZfF?p=preview
In the custom fancybox (aka lightbox, a dialog) I show contents with interpolated values.
in the service, in the "open" fancybox method, i do
open: function(html, $scope) {
var el = angular.element(html);
$compile(el)($scope); // how to know when the $compile is over?
$.fancybox.open(el); // the uncompiled is shown before the compiled
}
The problem is that the content in the dialog is loaded before the end of the $compile, so after less than a second i got a refresh of the dialog content with the values.
The plunkr works, but i want to avoid that the "el" is shown before it gets totally compiled: i want to show it only after the $compile has finished his job
Is there a way to know when the $compile it's over so i'll show the content on fancybox only after that?

You can't inject $scope into services, there is nothing like a singleton $scope.
So instead of $compile(el)($scope); try:
var compiledEl = $compile(el);
....
The $compile returns compiled data.
as a side note
I would provide service to directive and compile it into directive instead. I think it's the right way.

I've had the same problem with the ngDialog modals and popup provider. I needed to position the dialog based on its height. But the height depended on the compiled DOM.
I eventually found a solution using $timeout, like described in that post: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering/
For your code, it would give something like that:
open: function(html, $scope) {
var el = angular.element(html);
$compile(el)($scope);
$timeout(function() {
$.fancybox.open(el);
}, 0);
}

Related

Angular Bootstrap is creating duplicate bootstrap modals

I have a simple modal that appears when the user enters a page, but it is creating two of them. I have looked through the app and there are not two calls to the modal.
Here is the controller for it:
angular.module('rokoApp')
.controller('FinanceCtrl', function($scope, $modal) {
$modal.open({
templateUrl: 'includes/modal.html',
controller: function ModalInstanceCtrl($scope, $modal,$modalInstance){
console.log('opened')
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
});
will be much better if you give us an example of functional code in plunker or jsfiddle, because the problem could be in another place.
For example:
When we started creating an app with AngularJS usually we put ng-controller in a upper tag and write the first lines of our app. The problem is that some times when we added routing we forget remove the ng-controller and then the controller is executing twice. The first time with the configuration of the module and again with the processing of the html.
So the solution here is to remove the tag in the html if we use routing or delete the controller property of routing and keep the ng-controller in the html.
I will let you the two codes:
With the error: http://plnkr.co/edit/TmQ5QhjD55WTurQNaEIv
Without the error: http://plnkr.co/edit/1xGUGEvAZ6jUBs8CbhTT

Angular + Semantic UI Form Validations not woking [duplicate]

I have a simple website that implements jQuery in order to create a Slider with some images in the Index.html top banner.
Now, I want to use AngularJS so I'm breaking the HTML code into separate partials.
Header
Footer
Top Banner
If I run the Index.html in the original version (without applying AngularJS patterns) then I can see the slider working perfect.
When applying AngularJS patterns, I moved the top banner HTML to a partial html and then applied ng-view to the div where the top banner is originally located.
var app = angular.module('website', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.
when('/about',{templateUrl:'app/partials/about.html'}).
when('/contact',{templateUrl:'app/partials/contact.html'}).
otherwise({redirectTo:'/home',templateUrl:'app/partials/home.html'})
});
When I refresh the page the slider is not working, is rendered as simple html without any jQuery effect, is really a mess.
This partials has some jQuery plugins that usually activates by document.ready. But this event not fire when angular load partial in ng-view. How can i call this event to initialize jQuery plugins?
Any clue how to fix this?
Appreciate any help.
When you specify your routes, you can also specify a controller, so your routes would look like this:
var app = angular.module('website', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.
when('/about',{templateUrl:'app/partials/about.html', controller: 'aboutCtrl'}).
when('/contact',{templateUrl:'app/partials/contact.html', controller: 'contactCtrl'}).
otherwise({redirectTo:'/home',templateUrl:'app/partials/home.html', controller: 'homeCtrl'})
});
Now, you can define inside each controller what you want to do, jquery-wise, as part of a function, like this:
angular.module('website').controller('aboutCtrl', ['$scope', function ($scope) {
$scope.load = function() {
// do your $() stuff here
};
//don't forget to call the load function
$scope.load();
}]);
Make sense?
The other provided answers will work, but they are bound to controllers, and therefore not as scalable and reusable.
To do it the real "Angular" way as mentioned in the comments, you should be using a directive. The benefit to this is that you're able to create several instances with the same code, and can pass in attributes to the directive logic to "customize" the directive. Here's a sample of a way I've used it using bxSlider plugin:
JS:
app.directive('slider', ['$rootScope', function($rootScope) {
return {
restrict: 'EA',
templateUrl: '/path/to/template',
link: function(scope, iElement, attrs) {
//attrs references any attributes on the directive element in html
//iElement is the actual DOM element of the directive,
//so you can bind to it with jQuery
$(iElement).bxSlider({
mode: 'fade',
captions: true
});
//OR you could use that to find the element inside that needs the plugin
$(iElement).find('.bx-wrapper').bxSlider({
mode: 'fade',
captions: true
});
}
};
}]);
HTML:
<div slider some-attibute="some-attribute"></div>
And inside your directive template you could have the slider wrapper and slides, which you could build dynamically using ng-repeat bound to scope data.
I'd recommend reading this excellent article by Dan Wahlin about creating custom directives and how to fully harness they're power.
I had the same problem, I was loading some nav links in a ng-include and I have a script file called on my index.html with jquery instructions to make links active and It i not see the included content.
I tried all of the above solutions and for some reasons, none of them worked for me. When the content is not included (straight in the index.html) jquery kicks in fine but once included it stopped recognizing my elements.
So I simply wrapped my instructions in a setTimeout() function and it worked! Maybe it'll work for you too?
setTimeout(function() {
$("nav ul li").click(function() {
$("nav ul li").removeClass('active');
$(this).addClass('active');
});
});
Somehow the setTimeout() manages to load the script AFTER angular is done loading included content.
Happy coding everyone !
A Directive is certainly a good option, but you can also add a controller to any partial, which will perform all tasks (also with jQuery if you want) after the partial is loaded:
Example: partials/menu.html
<div ng-controller="partialMenuCtrl">
...
</div>
I had the same issue, I was running Jquery slick slider in simple html page it was working fine. How it works basically by including the slick.min.js file underneath the jquery.min.js file and then in script tags you need to initialize the plugin with options like e.g.
$('.items').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 3
});
now coming back to the issue, when I added Angular JS to my page and made partials of the page and then went back to the browser to check weather the page was working fine or not, the page was working fine except the slider. Then I tried to move those slick.min.js and plugin initialization to the partials, and it worked :)
How it worked I don't know the reason, since I am new to Angular but it worked and I am still wondering the reason.
I know it is an old thread but just for the sake of completion, you can use the following JQuery code. It is called event Delegation.
$("#anyDivOrDocument").on('click', '#targetDiv', function(event) {
event.preventDefault();
alert( 'working' );
});
I bought a html5 template and tried to integrate with my angularJS web app. I encountered the same issue. I solved it using:
Put the code below at where you put your <script src="vendor/61345/js/script.js"></script> code.
<script>
document.write('<script src="vendor/61345/js/script.js"><\/script>');
</script>

Onsen-UI: how to update the ons-screen page attribute and reload the view?

I've just started using Onsen UI by implementing the bootstrap example and I've been trying to get the view to update when I change the page attribute.
<body ng-controller="PageLoadingCtrl">
<ons-screen page="{{loadedPage}}"></ons-screen>
</body>
My controller's code:
app.controller('PageLoadingCtrl', ['$scope', '$timeout', 'notificationService',
function($scope, $timeout, sharedService){
$scope.loadedPage = "index.html";
$scope.updatePage = function(page){
$timeout( function (){
$scope.loadedPage = page;
$scope.$apply();
}, 500);
};
$scope.$on('changePage', function (event, message){
$scope.updatePage(message);
});
}
]);
As you can see I'm using a controller on the body object so that I can update the loadedPage variable however, when I fire the changePage event, the view doesn't change.
After checking the DOM elements with web inspector I can see that page attribute is equal to whatever I pass to the updatePage function.
So far I tried to force a refresh with $apply and $digest but that still doesn't do the trick.
Cheers!
Because ons-screen need to maintain page stack. it's not intuitive to use binding for the page attribute.
Using ons.screen.presentPage()/dismissPage()/resetPage() is the preferred way.

Angular UI Modal, inline template and controller

I want to create a really simple confirmation box using UI-modal, which I have successfully used to make complicated modals that load their template and controller from external files in the past.
It's so simple though that I don't want to rely on external template and controller files, just a simple box with a close button which is somehow wired up to a controller declared directly on the modal instance.
Here is what I have tried unsuccessfully...
var modalInstance = $modal.open({
template: "<div>Message goes here...<button ng-click='cancel()'>Continue</button></div>",
controller: function(){
$scope.cancel = function(){
alert("Cancelled");
};
}
});
Looks like you need to inject $scope into your controller function
controller: function($scope){
The scope of the modal template is not the same as the scope in the controller that you've defined the modal instance in.
The reason you're not getting undefined errors is $scope is a closure variable so adding .cancel() to it works just fine. But, since it isn't the same scope of the modal, so the ng-click doesn't see a .cancel() on its scope.
I replicated in this jsbin: http://jsbin.com/gejuxije/1/edit
Edit:
Since you mentioned you didn't want external files for a template, here's a demo of how to define the template for the modal inside the template of the view it is used on.
http://jsbin.com/gejuxije/2/edit
You can put html inside of an inline script...
<script type="text/ng-template" id="myModalTemplateName.html"></script>
The value you pass to 'template' needs to be valid HTML, and ideally should contain the appropriate modal CSS classes.
You may also need to pass in the scope for the controller.
var modalInstance = $modal.open({
scope:$scope,
template: "<div>Message goes here...<button ng-click='cancel()'>Continue</button></div>",
controller: function(){
$scope.cancel = function(){
alert("Cancelled");
};
}
});
In general I have not had to do this, but since you are defining the controller in the open method it may be necessary. According to the docs it should create a new scope as a child of rootScope, but I suspect your mileage is varying. I wish the instructions on the website were a little more informative on this topic.
You may also want to try $close and $dismiss. I've never tried them, but since you are not having luck with the scope variable these might be what you need.
I am just trying to do something similar and stumbled across this. I know it's old but it might help someone.
Simply put
modalInstance.close();
in the cancel function

How to add AngularJS directives to .NET WebForms Update Panels?

I have a project that uses legacy code in .NET and WebForms. The legacy code uses several Update Panels.
My hope is to use AngularJS without impacting the legacy code base.
<div ng-app="myApp">
<NS:TheUserControl ID="TheUserControl1" runat="Server" />
</div>
Here is the javascript:
var app = angular.module("myApp", []);
app.run(function ($rootScope, $compile) {
function insertDirective() {
jQuery(targetElementSelector).attr("my-directive", "");
}
insertDirective();
var mgr = Sys.WebForms.PageRequestManager.getInstance();
mgr.add_endRequest(function (sender, args) {
insertDirective();
$compile(jQuery(targetElementSelector))($rootScope);
});
});
The code above adds an attribute to an HTML element inside NS:TheUserControl, and the attribute specifies a directive (see directive below).
Then, these steps are used when the update panel changes:
Detect the change using Sys.WebForms.PageRequestManager (EndRequest listener)
Re-add the directive using javascript
Run $compile on the newly-inserted directive
Here is the directive:
app.directive("myDirective", function () {
return {
template: "<span ng-repeat='item in items'>{{item}}</span>"
+ "<span ng-transclude></span>"
, transclude: true,
, controller: function ($scope) {
$scope.items = ["a", "b", "c"];
}
};
});
This almost works... except...
Problem 1:
AngularJS creates a scope associated with each instance of a directive. When the update panel inside NS:TheUserControl changes the DOM, the previous scopes are still present. I can see this in Batarang (a Chrome developer tool for AngularJS).
Problem 2:
For a brief moment after the update panels change, I get:
abc <-- Initial page load
abcabc <-- Subsequent update panel changes
abcabcabc
abcabcabcabc
Then, a moment later after each update panel change, the content jumps back to the correct:
abc
Questions:
So, how do I either:
Remove the orphaned scopes?
Or, incorporate AngularJS directives in a way that plays nice with the update panels?

Categories

Resources