Stop Angular routing links inside ng-view - javascript

I'm using Angular JS to dynamically load content like so:
HTML
...
<div ng-controller="MainController">
<div ng-view></div>
</div>
</html>
Angular
(function(){
var app = angular.module('app', ['ngRoute', 'ngAnimate']);
app.config(function($routeProvider) {
$routeProvider.when('/test', {
templateUrl : 'views/test.html',
controller : 'MainController'
});
});
app.controller('MainController', function($scope){ });
})();
This works as expected. However, inside the file test.html I have some links with the href="#" that need to be handled with javascript to do various things. At the moment, Angular is interpreting them with it's routing method and treats them as links to the homepage. How do I stop this and treat the links the way I want?
Example test.html content:
Left
Right
<p>Test content</p>
In a JS file separate from Angular I tried:
$('.slideLeft').on('click',function(){
return false;
});
But it doesn't do the return false, it uses the Angular routing.

You should be using Angular for all your bindings including event bindings. Don't use .on('click'), use ng-click (or .bind if you really need it, but you probably don't).
You can also see from the docs that the <a> directive does nothing if href is empty. Use href="" rather than href="#"

Use href="javascript:void(0)" in anchor attribute and also you should use ngClick instead of binding element using jQuery.

Related

ng-controller within an include that is within another controller potential scope issue

I am using node and angularjs. I have a frame like page inside an ejs that is passed content to load into the includes dynamically.
<div ng-app="thisApp">
<div ng-controller='MainCtrl'>
{{ firstMessage }}
<div id='contentFromNode' ng-include='<%= pageContent %>'></div>
</div>
</div>
<script>
var thisApp = angular.module('thisApp', []);
thisApp.controller('MainCtrl', [ '$scope', function($scope) {
$scope.firstMessage = "Main Controller Working Fine";
}])
</script>
and then the passed content might be just an html page containing something like this:
<div ng-controller='NestedCtrl' id='content-type-container'>
{{ nestedMessage }}
</div>
<script>
thisApp.controller('NestedCtrl', [function(){
var nested = this;
nested.nestedMessage = "Nested Won't Work";
}])
</script>
So I have tried $scope within the NestCtrl instead of referencing this, I have tried moving the script tag above and below (ideally this get separated eventually anyway). I have tried aliasing the controllers, however my problem is the in registration of the controller itself as I get that great Error: [$controller:ctrlreg] error. The page is loading the content fine? Any ideas what I am doing wrong here?
Seems JQlite doesn't support this. You have to include jquery or lazy load the script. Refer
AngularJS: How to make angular load script inside ng-include?

How to insert one html page into another html page using custom directive in AngularJS?

Using custom directives, I want to add one HTML page into another, how can this be done?
The custom directive is as below:
(this is the .js file)
fbModule.directive('fbLogin', function(){
return {
template : html
}
})
And the html page to be included is:
(this is the .html file to be included)
<div ng-controller="fbCtrl">
<button ng-click="doFacebookLogin">
<img src="modules/shippingAddress/fastfill_fb.png" width="140px" height="25px;" style="margin-right: 8px; cursor:pointer">
</button>
</div>
The page inside which the above code should come is:
(this is the .html file in which the above html should come)
<div fbLogin></div>
<div style="font-size: x-small; color: black;">Save on typing. Use your FB data.</div>
Please help..
Thanks in advance
You should be using ngInclude to inject HTML into another page
https://docs.angularjs.org/api/ng/directive/ngInclude
<ng-include src="somehtmlfile.html"></ng-include>
you need to change template to templateUrl if you need to get the external html like as shown below.
templateUrl can also be a function which returns the URL of an HTML
template to be loaded and used for the directive. Angular will call
the templateUrl function with two parameters: the element that the
directive was called on, and an attr object associated with that
element.
Working Demo
fbModule.directive('fbLogin', function() {
return {
template: 'template.html'
};
});
to
fbModule.directive('fbLogin', function() {
return {
templateUrl: 'template.html'
};
});
Basically:
fbModule.directive('fbLogin', function(){
return {
templateUrl : "...path to html"
}});
...but read the Developers Guide https://docs.angularjs.org/guide/directive
use templateUrl instead of template. your templateUrl must point to the html file in directory.
here my templeUrl points to my.html that is inside template directory.
fbModule.directive('fbLogin', function(){
return {
templateUrl : "/templates/my.html"
}
})
If you want to completely replace directive tag with html file loaded by directive you should use templateUrl: 'path/to/file.html' and replace: true so your directive tag gets replaced by html instead of being included into it.
Here is the directive example:
app.directive('fbLogin', function(){
return {
templateUrl : 'include.html',
replace: true
}
});
Also, here is the working plunker.

Add <object> with custom attributes using AngularJS controller

I'm attempting to add an <object></object>into my html using a controller. When I load a <div> or a <p>, it works properly, but when I add an <object> it doesn't appear, nor do any custom attributes.
HTML:
<html ng-app="myAngularSite">
...
...
<div ng-controller="MyController">
<div id="myloader" ng-bind-html="myObject"></div>
</div>
JS:
var app = angular.module('myAngularSite', ['ngRoute']);
angular.module('myAngularSite', ['ngSanitize'])
.controller('MyController', ['$scope',function($scope) {
$scope.myObject =
'<object id="my_object" data="mysite.html" width="99.5%" height="400px" style="overflow:auto;border:3px ridge gray"/>';
}]);
How can I add the custom attributes and the object into my site? I noticed that attributes won't appear when I try to load a <div id"with_attribut></div> with attributes, although the divs appear by themselves.
Thanks!
The custom directive is probably the good solution, you can always add more custom behaviours. With ngBindHtml you will be limited. Here is link which can help you:
angular ng-bind-html and directive within it

Embedding AngularJS in existing jquery/bootstrap based website

We've got an existing application where the client-side is jQuery / Bootstrap. It consists of many tabs where each tab is defined in a module imported via. require.js. The tab javascript is handed a parent DOM element and is in charge of drawing itself inside of that element.
We'd like to start building new functionality (tabs) in AngularJS and running into some problems doing that.
My thinking is that we could tag the body with ng-app and in the main page code conjur up an app module window.app = angular.module('ourApp', []); and later, as tabs are loaded, create and wire-up the controllers.
I've built a simple single-page example that exhibits the problem we are having (below or here http://jsfiddle.net/p4v3G/1/).
The only way I've been able to get the example to work is manually calling angular.bootstrap which I'm pretty sure is wrong. Also, that only works the first time so if I click the button twice (equivalent to navigating to the tab, away from it, and back again within our app), Angular isn't wired up properly.
I'd appreciate any help.
<body ng-app='testApp'>
<div id="main" style="border: 1px solid #000; background: #ffdddd;">Click button to replace template and wire up controller...</div>
<button id="button1">Load</button>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
<script>
var app = angular.module('testApp', []);
jQuery(function() {
$("button").click(function() {
// controllers are wired up in click handler to simulate environment where we
// are looking to embed angular inside of an existing bootstrap/jquery application
// where new tabs (loaded as separate modules through require) are loaded on-demand.
app.controller('TestController', function($scope) {
$scope.message = 'Hello World, from Controller #1';
});
$("#main").html('<div ng-controller="TestController">{{message}}</div>');
// Bootstrap works the first click but not subsequent clicks
angular.bootstrap(document, ['testApp']);
});
});
</script>
</body>
To chunk up your appliation so that only the relevant parts are instantiated etc. what you need is angular ui-router. You would then set up a parent state for your tab-control with child states for each of your tabs. That way you both get deep linking and the performance you want with loading only the relevant tab.
As for requirejs, I encourage you to firstly consider if you really need it. In my opinion the javascript making up an angular application is usually much terser than a jquery application due to the declarative nature of the technology. Therefore loading all of the javascript at boot-time is ok. Your templates however may not be as simple, but by using templateUri references to templates they may be loaded as needed. (Personally I prefer compiling them to javascript and placing them in the $templateCahce at the cost of boot-time, but that's another matter.)
That being said, if my observations do not hold for your scenario/application/codebase, then others have had great success incorporating requirejs with angularjs. For a nice introductory talk on that subject see this nice ng-conf video.
Best of luck!
Could you be more precise, what type of errors appears.
You don't need use jquery. Check this code and compare
http://jsfiddle.net/pokaxperia/3w6pb/1/
HTML
<body ng-app='testApp'>
<div ng-controller="TestController">
<span id="main" style="border: 1px solid #000; background: #ffdddd;">{{message}}</span>
<button ng-click="loadMessage();" id="button1">Load</button>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</body>
script
var app = angular.module('testApp', []);
app.controller('TestController', ['$scope',function($scope) {
$scope.message = "Click button to replace template and wire up controller...";
$scope.loadMessage = function(){
$scope.message = 'Hello World, from Controller #1';
};
}]);
Or check your code on jsfiddle, but with few variants
http://plnkr.co/edit/fUQDpO?p=preview
HTML
<body>
<example-tabs></example-tabs>
<div class="panel" ng-show="isSelected(1)">Panel One</div>
<div class="panel" ng-show="isSelected(2)">Panel Two</div>
<div class="panel" ng-show="isSelected(3)">Panel Three</div>
</body>
Main script:
var app = angular.module('tabsExample', ['tabDirectives']);
Directive to load Tabs
var app = angular.module('tabDirectives', []);
app.directive('exampleTabs', [
function() {
return {
restrict: 'E',
templateUrl: 'example-tabs.html',
controller: function($scope) {
$scope.tab = 1;
$scope.selectedTab = function(setTab) {
$scope.tab = setTab;
};
$scope.isSelected = function(checkTab) {
return $scope.tab === checkTab;
};
}
};
}
]);

Using Waypoints.js inside an AngularJS view

I am trying to use Waypoints inside a scrollable AngularJS view, however it's not working. I am trying to use ui.utils jQuery Passthrough but nothing happens. Here's what I have so far:
<body>
<div id="wrapper">
<div id="nav-menu">
<...>
</div>
<div id="main" class="main">
<div ng-view></div>
</div>
</div>
</body>
I am using the following template for the view:
<div class="fullScreenImage"></div>
<div ui-jq="waypoint" ui-options="test">test</div>
and my controller looks something like this:
app.controller('myController', ['$scope',
function ($scope) {
$scope.test = function(){
alert('You have scrolled to an entry.');
}}]);
My main element is scrollable but the window is not. Setting passthrough to the main div will trigger the test function, however I need it inside the template. Any suggestions?
Providing a JSFiddle or plunkr would be helpful.
But I suppose the issue is because the template is inside ngView.
As the content of the template is placed inside the ngView via XHR, the waypoints needs to be refreshed as discussed in the link http://imakewebthings.com/jquery-waypoints/#doc-refresh
An Angular directive will be more effective IMHO.
I had trouble with waypoints nested in ng-views as well.
My solution was just to wait till after the view had loaded to bind the waypoints, for this you can use $viewContentLoaded.
E.g.
myApp.run(['$rootScope', function($rootScope) {
$rootScope.$on('$viewContentLoaded', function(){
var waypoint = new Waypoint({
element: document.getElementById('waypoint'),
handler: function(direction) {
console.log('Scrolled to waypoint!')
}
})
});
}]);
I had the same problem. It's also possible to delay the binding with $timeout e.g $timeout(addWaypoints());.

Categories

Resources