Loading jQuery script after Angular route / view loads - javascript

I am just learning AngularJS. I currently have a simple SPA that loads two containers, switching one after another depending on the URL.
Navigation Links
- Casefilm
- Videos
Using basic Angular Routing, I am able to load both successfully. However, one of the pages (videos.php) contain a slideshow script that is based on jQuery and a simple Bootstrap modal to load fullscreen Youtube videos. When this page is called, Angular loads the view but for some reason does not recognize the jQuery instance.
Here's my Videos view code:
<div id="videos" class="row">
<div class="col-md-12">
<div id="video-carousel">
<div><img ng-src="assets/images/thumb1.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb2.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb3.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb4.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb5.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb6.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb7.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb8.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb9.jpg" class="img-responsive" alt=""></div>
<div><img ng-src="assets/images/thumb10.jpg" class="img-responsive" alt=""></div>
</div>
</div>
</div><!-- #videos -->
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div>
<iframe width="100%" frameborder="0" allowfullscreen=""></iframe>
</div>
</div>
</div>
</div>
</div>
Here's my app.js:
var humanApp = angular.module('humanApp', ['ngRoute']);
humanApp.controller('HumanCtrl', ['$scope', '$http', function (scope, http){
http.get('videos.json').success(function(data){
scope.videos = data;
});
}]);
humanApp.config(function ($routeProvider){
$routeProvider
.when('/casefilm',
{
controller: 'HumanCtrl',
templateUrl: 'assets/partials/casefilm.php'
})
.when('/videos',
{
controller: 'HumanCtrl',
templateUrl: 'assets/partials/videos.php'
})
.otherwise({ redirectTo: '/casefilm' });
});
humanApp.directive('slickSlider',function($timeout){
return {
restrict: 'A',
link: function(scope,element,attrs) {
$timeout(function() {
$(element).slick(scope.$eval(attrs.slickSlider));
});
}
}
});
And lastly, this is what is on my index.php before the </body> tag:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.0/angular-route.min.js"></script>
<script src="assets/scripts/app.js"></script>
<script src="assets/scripts/jquery.js"></script>
<script src="assets/scripts/bootstrap/bootstrap.min.js"></script>
<script src="assets/scripts/slick.min.js"></script>
<!--<script src="assets/js/owl.carousel.min.js"></script>-->
<script>
$(document).ready(function() {
$("#video-carousel").slick(
{
infinite: true,
dots: true,
arrows: false,
slidesToShow: 2,
slidesToScroll: 2
}
);
$(function(){
$('iframe').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
// If you want to keep full screen on window resize
$(window).resize(function(){
$('iframe').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
});
});
function autoPlayYouTubeModal(){
var trigger = $("body").find('[data-toggle="modal"]');
trigger.click(function() {
var theModal = $(this).data( "target" ),
videoSRC = $(this).attr( "data-thevideo" ),
videoSRCauto = videoSRC+"?autoplay=1;rel=0;html5=1" ;
$(theModal+' iframe').attr('src', videoSRCauto);
$(theModal+' button.close').click(function () {
$(theModal+' iframe').attr('src', videoSRC);
});
});
}
autoPlayYouTubeModal();
});
</script>
Summary:
Angular routing works.
jQuery is not working when my Video view is called.
Question:
Am I missing something?
Is there a better way to deal with this?

use RequireJS . in requirejs you can set dependency.
Here is some example given :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="require.js"></script>
<script type="text/javascript">
// override require function, with it's "rebinded" version
window.require = require.bind(this, {
// set baseUrl once and for all
'baseUrl': '/some/absolute/path/and_another_one/'
});
</script>
</head>
<body>
<script type="text/javascript">
require([
"myModule1.js",
"myModule2.js"
], function($myModule1, $myModule2) {
// do something here...
});
</script>
</body>
</html>
You can find more at :
http://www.angrycoding.com/2011/09/managing-dependencies-with-requirejs.html

Related

Ng repeat not working in kenwheeler - Angular Js

Hi I am using kenwheeler slick carousel but when I use ng-repeat on the div i get `listed images'.
What I a doing wrong here ?
<section class="regular slider" style="clear: both" ng-if="slides">
<div ng-repeat="slide in slides">
<img src="{{slide.path}}">
</div>
</section>
I tried the solutions provided here angular slick although its different but still no proper images are being displayed. without ng-repeat it works perfect.
The output is something like this image
My controller
$scope.single_product = function (product_id) {
$http.get('abc',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.product = data;
$(".regular").slick({
dots: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000
});
})
.error(function (data) {
console.log(data);
});
};
I am including slick.css slick-theme.css and slick.jshere is the link to all Files
Instead of src Use ng-src ng-src use to get the path of image in angularJS
Go through this link carefully and apply styles
http://kenwheeler.github.io/slick/
remove div that contains ng-repeat
<section class="regular slider" style="clear: both" ng-if="slides">
<img ng-repeat="slide in slides" ng-src="{{slide.path}}">
</section>
Use ng-src
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
$scope.slides = [{
path: 'https://cloud.githubusercontent.com/assets/1734769/3162502/f49ff416-eb35-11e3-8f47-3a85f8abfd84.png'
}, {
path: 'https://cloud.githubusercontent.com/assets/1734769/3162502/f49ff416-eb35-11e3-8f47-3a85f8abfd84.png'
}, {
path: 'https://cloud.githubusercontent.com/assets/1734769/3162502/f49ff416-eb35-11e3-8f47-3a85f8abfd84.png'
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<section class="regular slider" style="clear: both" ng-if="slides">
<div ng-repeat="slide in slides">
<img ng-src="{{slide.path}}">
</div>
</section>
</div>
Try this:
<div ng-repeat="slide in slides">
<img ng-src="slide.path">
</div>
Check angular-slick README and include all css and js. Add slick to your angular.module [ let say MyApp ] dependency and use slick directives. I think you missed to use slick directives.
<section class="regular slider" style="clear: both" ng-if="slides">
<slick slides-to-show=3 slides-to-scroll=3>
<div ng-repeat="slide in slides">
<img src="{{slide.path}}">
</div>
</slick>
</section>

Use AngularJS $http.get to repeatedly request JSON array on scrolling

Below is a snippet using AngularJS to get the JSON response.
On scrolling to the bottom of the page, I need to request repeatedly till the JSON array list is empty.
<section>
<div style="padding-top:60px" infinite-scroll="myPagingFunction()" infinite-scroll-distance="3" ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="news in newsList">
<div class="col-lg-3 col-md-4 col-sm-6" style="">
<div class="thumbnail">
<img src="{{news.coverUrl}}" class="img-responsive" alt="{{news.name}}"/>
<div class="caption">
<h4>{{news.name}}</h4>
</div>
</div>
</div>
<div class="visible-lg clearfix" ng-if="($index+1)%4 == 0"></div>
<div class="visible-md clearfix" ng-if="($index+1)%3 == 0"></div>
<div class="visible-sm clearfix" ng-if="($index+1)%2 == 0"></div>
</div>
</div>
</section>
<script src="js/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="js/ng-infinite-scroll.min.js"></script>
<script>
var offset = 0
var maxCount = 20
var app = angular.module('myApp', ['infinite-scroll']);
function myPagingFunction(){
app.controller('myCtrl', function($scope, $http) {
$http.get("news.json").then(function(response) {
$scope.newsList = response.data;
});
});
}
myPagingFunction();
</script>
<script src="js/bootstrap.min.js"></script>
Kindly help me in solving this.
Using jQuery + angular is not good
You must use angular way instead, and write some directives or listeners in run phase, but here's a better approach - use `ngInfiniteScroll plugin
You can simply use infinite Scroll services to easily achieve this ,
<ANY infinite-scroll='{expression}'
[infinite-scroll-distance='{number}']
[infinite-scroll-disabled='{boolean}']
[infinite-scroll-immediate-check='{boolean}']
[infinite-scroll-listen-for-event='{string}']>
Add ng-infinite scroll module in your application
for more info refer this [Documentation]:(https://sroze.github.io/ngInfiniteScroll)
You can use this simple directive and enjoy:
app.directive("scroll",['$window', function ($window) {
return function (scope, element, attrs) {
angular.element($window).bind("scroll", function () {
if (document.body.scrollHeight - $window.scrollY < 890) {
scope.$apply(function () {
scope.myPagingFunction();
});
}
});
};
}]);
and you can use this code for your situation
<section>
<div style="padding-top:60px" scroll ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="news in newsList">
<div class="col-lg-3 col-md-4 col-sm-6" style="">
<div class="thumbnail">
<img src="{{news.coverUrl}}" class="img-responsive" alt="{{news.name}}"/>
<div class="caption">
<h4>{{news.name}}</h4>
</div>
</div>
</div>
<div class="visible-lg clearfix" ng-if="($index+1)%4 == 0"></div>
<div class="visible-md clearfix" ng-if="($index+1)%3 == 0"></div>
<div class="visible-sm clearfix" ng-if="($index+1)%2 == 0"></div>
</div>
</div>
</section>
<script src="js/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="js/ng-infinite-scroll.min.js"></script>
<script>
var offset = 0
var maxCount = 20
var app = angular.module('myApp', ['infinite-scroll']);
app.controller('myCtrl', function ($scope, $http) {
$scope.myPagingFunction= function() {
$http.get("news.json").then(function (response) {
$scope.newsList = response.data;
});
}
});
app.directive("scroll",['$window', function ($window) {
return function (scope, element, attrs) {
angular.element($window).bind("scroll", function () {
if (document.body.scrollHeight - $window.scrollY < 890) {
scope.$apply(function () {
scope.myPagingFunction();
});
}
});
};
}]);
</script>
<script src="js/bootstrap.min.js"></script>

materialbox Materializecss works only after typing initialization jQuery in console

I have used '.materialboxed' in my webpage, but the initialization in script doesn't work, I have to manually type $('.materialboxed').materialbox(); in console for it to work.
Html (ui-view in angular route)
<div class="row">
<div class="card-panel col l12" style="height: 750px;">
<img class="col l5 materialboxed" height="500px" id="poster"
ng-src="https://image.tmdb.org/t/p/original{{poster_path}}"/>
<div class="col l7">
<div class="row">
<a class="col l10" style="float:left;text-align: left;" ng-href="{{homepage}}">
<h3 class="title" ng-bind="original_title"></h3>
</a>
<a ng-href="http://www.imdb.com/title/{{imdb_link}}"
style="float:right;text-align: right; margin-top: 29px;"
class="imdb-link col l2" title="IMDb"><i class="icon-imdb"></i></a>
</div>
<div class="row"><p ng-bind="overview"></p>
<span class="right" ng-bind="release_date"></span>
<h5>Genres</h5>
<p ng-bind="genre"></p>
<h5>Production Companies</h5>
<p ng-bind="names">
</p>
<h5>Voting</h5>
<p ng-bind="vote_average"></p></div>
</div>
</div>
</div>
See the in 3rd line.
index.html
//rest code
<main ui-view></main>
</div>
<script src="js/angular_min.js"></script>
<script src="js/angular-touch.min.js"></script>
<script src="js/angular-ui-router.min.js"></script>
<script src="js/angucomplete-alt.js"></script>
<script src="appRoute.js"></script>
<script src="controller/MovieController.js"></script>
<script src="controller/LoginController.js"></script>
<script src="controller/RegisterController.js"></script>
<script src="controller/TvController.js"></script>
<script src="controller/LoggedInController.js"></script>
<script src="controller/TopMovieController.js"></script>
<script src="app-services/DetailsService.js"></script>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/materialize.min.js"></script>
<script>
$(document).ready(function () {
$('.materialboxed').materialbox();
$('.button-collapse').sideNav({
menuWidth: 300,
edge: 'left',
closeOnClick: true
}
);
$('.modal-trigger').leanModal();
$("#movie").click(function () {
window.location.href = window.location.pathname + "#/movie";
});
$("#tv").click(function () {
window.location.href = window.location.pathname + "#/tv";
});
});
</script>
</body>
Even after initializing the materialboxed, it doesn't work. It works only after typing $('.materialboxed').materialbox(); in console manually.
Help me figure this out. Thanks
You shouldn't use $(document).ready in Angular. In fact you should try to use as little jQuery as possible, but if you need to, then you should create a directive that allows you to initialize the function after they render.
var app = angular.module('myApp');
app.directive('onLastRepeat', function() {
return function(scope, element, attrs) {
if (scope.$last)
setTimeout(function() {
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
});
app.controller('MoviesController', function($scope) {
$scope.$on('onRepeatLast', function(scope, element, attrs) {
$('.materialboxed').materialbox();
});
}
Now you can apply this to your HTML:
<ul>
<!-- this is just an example with the added directive -->
<li ng-repeat="movie in movies" on-last-repeat>
<img ng-src="{{imageObjectHere}}" class="materialboxed">
</li>
</ul>
Since you added this new directive in there, the $('.materialboxed').materialbox(); should fire after the repeat is done

how to give dynamic path to image on lightbox modal in angularjs along with ng-view?

I downloaded a template and applying Angularjs to that template.That template uses various Jquery plugins such as flexslider,Chocolat(Light box plugin)etc.
my code snippets are as above
index.html
<head>
<link rel="stylesheet" href="css/chocolat.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.chocolat.js"></script>
<script type="text/javascript" type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" type="text/javascript" src="js/angular-route.min.js"></script>
</head>
<div class="banner ban1">
<div class="container">
<div class="top-menu">
<span class="menu"><img src="images/nav.png" alt=""/> </span>
<ul>
<li>home
</li>
<li><a ng-class="{active: isActive('/about')}" href="/curabitur/#/about">about</a>
</li>
<li><a ng-class="{active: isActive('/menu')}" href="/curabitur/#/menu">menus</a>
</li>
<li><a ng-class="{active: isActive('/gallery')}" href="/curabitur/#/gallery">gallery</a>
</li>
<li><a ng-class="{active: isActive('/events')}" href="/curabitur/#/events">events</a>
</li>
<li><a ng-class="{active: isActive('/contact')}" href="/curabitur/#/contact">contact</a>
</li>
</ul>
</div>
</div>
</div>
<body>
<div ng-view class="content"></div>
</body>
<script type="text/javascript" src="js/services.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<script type="text/javascript" src="js/app.js"></script>
I implemented routing using ng-view
in my gallery.html as template(/gallery)
<div class="gallery-info" style="border : 1px solid;">
<div class="col-md-4 galry-grids moments-bottom" ng-repeat=" gallery in galleryCollection.galleryItems" style="border : 1px solid green;">
<a light-box class="b-link-stripe b-animate-go" ng-src="{{gallery.galleryImageUrl}}"> {{gallery.galleryImageUrl}}
<img src="{{gallery.galleryImageUrl}}" class="img-responsive" alt="">
<div class="b-wrapper">
<span class="b-animate b-from-left b-delay03">
<img class="img-responsive" src="{{gallery.galleryBigImageUrl}}" alt=""/>
</span>
</div>
</a>
</div>
<div class="clearfix"></div>
</div>
and app.js as
angular.module("curabitur", ['ngRoute', 'curabitur.controller'])
.config(function($routeProvider) {
$routeProvider
.when("/gallery", {
templateUrl: './partials/gallery.html',
controller: 'galleryController'
})
.when("/menu", {
templateUrl: './partials/menu.html',
controller: 'menuController'
})....other when blocks
});
the controller for gallery is in controller.js as
angular.module("curabitur.controller", ['ui.bootstrap', 'curabitur.services'])
.directive('lightBox', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log("lightbox directive");
console.log("lightbox function");
$(element).Chocolat();
$('.moments-bottom a').Chocolat();
$(function() {
$('.moments-bottom a').Chocolat();
//alert($('.moments-bottom '));
});
}
};
})
.controller("galleryController", function($scope) {
$scope.galleryCollection = {
"galleryId": "",
"galleryHeading": "EVENTS",
"galleryItems": [{
"galleryImageId": "",
"galleryImageUrl": "images/g1.jpg",
"galleryBigImageUrl": "images/e.png",
"galleryimageLink": ""
}, {
"galleryImageId": "",
"galleryImageUrl": "images/g2.jpg",
"galleryBigImageUrl": "images/e.png",
"galleryimageLink": ""
}, ]
};
My question is that How should I assign dynamic value to in
gallery.html where light-box directive is called?
After clicking image in div image path is not getting to
I also tried ng-href but it doesn't work.
I referred following link.
anchor tags and dynamic views in angular.js
You can use ng-src directive like this ng-src="{{gallery.galleryBigImageUrl}}"
It will tell anguar to load image after binding
Inside light-box directive in controller.js, I accessed the element and set the href property to that element as,
.directive('lightBox', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log("lightbox directive");
console.log("lightbox function");
/* set image url attribute */
element.attr("href",scope.gallery.galleryImageUrl)
/* call to plugin */
$(element).Chocolat();
$('.moments-bottom a').Chocolat();
$(function() {
$('.moments-bottom a').Chocolat();
//alert($('.moments-bottom '));
});
}
};
});
and put # to in gallery.html as
<a light-box class="b-link-stripe b-animate-go" href="#">
<img src="{{gallery.galleryImageUrl}}" class="img-responsive" alt="">
<div class="b-wrapper">
<span class="b-animate b-from-left b-delay03">
<img class="img-responsive" src="{{gallery.galleryBigImageUrl}}" alt=""/>
</span>
</div>
</a>

jQuery functions never getting executed on .ready()

I'm a little new to jQuery and I am having some issue wiring up my click events. If I put an alert(''); I can see that menu.js is referenced properly but when I alert from inside the .ready() function the alert is never triggered...
JSFiddle: Click Here
Could someone be kind enough to point out my issue? Thanks!
HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Menu Demo</title>
<link href="Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="Content/MenuDemo.css" rel="stylesheet" />
</head>
<body>
<div class="navbar">
<img id="navbar-logo" src="Content/images/ingr_logo.png" class="ui-button-icon-primary">
<img id="navbar-logo" src="Content/images/smaller.png" class="image-right">
</div>
<div id="menu1" class="floating-menu ui-menu">
<div class="floating-menu-header">
<div class="floating-menu-header-text">Example Menu</div>
<div class="grip"></div>
<div><img id="expand1" src="Content/images/Expand.png" class="floating-menu-header-icons"></div>
<div><img id="drag1" src="Content/images/Lock-Add.png" class="floating-menu-header-icons locked"></div>
<div><img id="close1" src="Content/images/Close.png" class="floating-menu-header-icons"></div>
</div>
<div class="floating-menu-body"></div>
</div>
<div id="menu2" class="floating-menu ui-menu">
<div class="floating-menu-header">
<div class="floating-menu-header-text">Example Menu</div>
<div class="grip"></div>
<div><img src="Content/images/Expand.png" class="floating-menu-header-icons"></div>
<div><img src="Content/images/Lock-Add.png" class="floating-menu-header-icons locked"></div>
<div><img src="Content/images/Close.png" class="floating-menu-header-icons"></div>
</div>
<div class="floating-menu-body"></div>
</div>
<div id="menu3" class="floating-menu ui-menu">
<div class="floating-menu-header">
<div class="floating-menu-header-text">Example Menu</div>
<div class="grip"></div>
<div><img src="Content/images/Expand.png" class="floating-menu-header-icons"></div>
<div><img src="Content/images/Lock-Add.png" class="floating-menu-header-icons locked"></div>
<div><img src="Content/images/Close.png" class="floating-menu-header-icons"></div>
</div>
<div class="floating-menu-body"></div>
</div>
<div id="menu4" class="floating-menu ui-menu">
<div class="floating-menu-header">
<div class="floating-menu-header-text">Example Menu</div>
<div class="grip"></div>
<div><img src="Content/images/Expand.png" class="floating-menu-header-icons"></div>
<div><img src="Content/images/Lock-Add.png" class="floating-menu-header-icons locked"></div>
<div><img src="Content/images/Close.png" class="floating-menu-header-icons"></div>
</div>
<div class="floating-menu-body"></div>
</div>
<!-- Scripts-->
<script src="Scripts/libs/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="Scripts/libs/jquery-ui-1.10.4.min.js" type="text/javascript"></script>
<script src="Scripts/site/menu.js" type="text/javascript"></script>
</body>
</html>
menu.js
/// <reference path="../jquery-2.1.1.js" />
/// <reference path="../jquery-ui-1.10.4.js" />
// Make Menus Draggable
function makeMenusDragHandler() {
$('.locked').click(function () {
$('.floating-menu').draggable();
});
}
// Collapse/Expand Height of Navbar
function smallBigNavbarHandler() {
$('.image-right').click(function () {
var navbar = $('.navbar');
navbar.height(navbar.height() === 51 ? 30 : 15);
});
}
$(document).ready(function ($) {
// add handlers
smallBigNavbarHandler();
makeMenusDragHandler();
// setters
});
You have two issues:
You don't have jQuery included
See below
This line:
navbar.height = navbar.height() === 51 ? 30 : 15;
should be:
navbar.height(navbar.height() === 51 ? 30 : 15);
The setter is:
.height(value)
and not
.height = value

Categories