AngularJS - Dynamic HTML that contains the controller code - javascript

I have a AngularJS page that displays a popup. The HTML for the popup is dynamically retrieved from the server using an AJAX call. This dynamic HTML contains a new controller and the necessary AngularJS code for the controller as well.
This code works only if the child page JavaScript code is present in the parent page.
I would like to keep all the child page code in the child page itself.
Can someone please point out what I am doing wrong?
Main Page
<div id="mainPage" ng-controller="mainController">
Contains a table that displays a bunch of rows.
</div>
<div id="popup">
Dynamic HTML retrieved from AJAX goes here.
</div>
<script type="text/javascript">
angularMainApp.controller('mainController', ['$scope', '$http', '$compile', function ($scope, $http, $compile)
{
$scope.activateView = function(ele)
{
$compile(ele.contents())($scope);
$scope.$apply();
};
$scope.buttonClick = function()
{
$("#popup").html( dynamicHTMLThroughAJAX );
$scope.activateView($("#divCreateTemplatePopup"));
return;
}
return;
}]);
</script>
Dynamic HTML Content
<div ng-controller='childController'>
Some HTML here.
</div>
<script type="text/javascript">
angularMainApp.controller('childController', ['$scope', '$http', function ($scope, $http)
{
}]);
</script>

Angular need to know that you changed the content and realize that it should update it self too .
so , what you have to do is tel him that apply the watchers and other stuff to the current DOM .
for doing that you shall use $scope.$apply(); . by calling this function you force angular to add watchers and other stuff's to the DOM and now it can work with you'r new contents too .
i suggest you to read about digest in angularjs and see how it works .
here's some link about your problem to see the problem better :
AngularJS and scope.$apply
Digest cycle and $scope
AngularJs docs : $scope.$apply()
When to use $scope.$apply()
AngularJS: $watch, $digest and $apply
good luck and have fun .

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?

querySelectorAll in AngularJS partial ng-view

I'm trying to use queryselectorAll to get all elements with a certain class name. I have a problem where I can only get results from elements in the index.html page. If I try to get a nodelist from a partial (ng-view) html page I get an empty result back.
App.js
var myApp = angular.module('myApp', ['ngRoute', 'articleControllers']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main', {
templateUrl: 'lib/partials/main.html',
controller: 'MainController'
})
}]);
controller.js
var articleControllers = angular.module('articleControllers', []);
articleControllers.controller('MainController', ['$scope', '$http', function ($scope, $http){
$http.get('http://...').success(function(data) {
$scope.articles = JSON.parse(data);
});
}]);
index.html
(body, header, ...)
<section ng-view>
</section>
(footer, ...)
lib/partials/main.html
...
<div class="nextArticle">
<button class="next_btn" title="View next article"> link text</button>
</div>
...
finally: helper.js (which is a script I call like every other script in index.html)
var elList = document.querySelectorAll('.next_btn');
Array.prototype.forEach.call(elList, function(el) {
console.log("Found: " + el);
});
So to recap:
Its like querySelectorAll can only find elements in the index.html and not in the partial views with ng-view.
Anyone an idea of what could be wrong?
I'm trying not to use jquery.
Move your helper.js code to custom directive. https://docs.angularjs.org/guide/directive
What are Directives?
At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.
That is because ng-view load the template after angular gets loaded, and the JS code which you have added is firing before the ng-view renders the template, I think you could solve this by writing a directive for ng-view that will will fire your jQuery code once your ng-view content gets loaded
Basically you need to wrap your code in element.on('load' event so that it will ensure that code will available when jQuery code is firing
app.directive('ngView', ['$timeout', function($timeout){
return {
restrict: 'AE',
link: function(element, attrs){
$timeout(function(){
element.on('load', function(event){
//your jQuery code will lie here
//that will also get the DOM of ng-view template
});
});
}
}
}]);

Angular animate parent div of ng-view using element insde ng-view

Is it possible to css animate a div (background-color) that is outside the ng-view, using a directive on a $state inside the ng-view?
The ng-view has css animations for the routing.
If I do not animate the div then the ng-view anims work fine, but..
If I add animation classes to the div(bgId) then the routing anims do not fire.
Here is a sample of html: (Button added as example - would normally be in the template pages eg. home.html / login.html )
<body ng-app="app" ng-controller="MainCtrl">
<div id="bgId" class="{{colorVal}}">
<ion-nav-view animation="slide-left-right">
</ion-nav-view>
</div>
<button swapcolour="changeColour()" data-nxtpage="1">change colour</button>
</body>
This is controlled by a directive(swapcolour) that gets the nxtpage value from the button attr and updates the colorVal in MainCtrl.
//MainCtrl.js
.controller('MainCtrl', ['$scope', '$state', function($scope, $state) {
$scope.colorVal = 'redBg';
}])
//Directive.js
.directive('swapcolour', function ($rootScope, $state) {
var pageArr = [{home:'redBg'},{login:'blueBg'}];
return function (scope, element, attrs) {
var nextPageNum = attrs.nxtpage;
var obj = pageArr[nextPageNum];
var item = Object.keys(obj);
var objItem = obj[item];
element.bind('click', function () {
$state.transitionTo(item[0]);
$rootScope.$$childHead.colorVal = objItem;
});
}
}])
I do not know why it fails. Any ideas?? I am new to directives. (Trying to setup a plunker, but having issues getting ionic working with it)
I fixed it! - I think.
Basically after totally stripping the application to its bones I managed to build a plunker and got it working.
There was nothing wrong with my code after all.
<body ng-app="app" ng-controller="MainCtrl">
<div id="bgId" class="{{colorVal}}">
<ion-nav-view animation="slide-left-right">
</ion-nav-view>
</div>
</body>
http://plnkr.co/edit/Oug8zD?p=preview
Then I tried this code on my app - and it still did not work! So I tried replacing my ionic.bundle.js and ionic.css files (orig installed using npm) with the files used in the plunker (1.0.0-rc.1) and my app worked :)
Hope this helps others in trouble in the future.

Jquery append() not working with angularjs

We are working with jquery 1.9.1 and angular 1.2.13. We are using a wysiwyg editor that works great, we save the html into the database and load the html back using jquery append function and works fine. Now we are trying to append the same html into a div tag (the wysiwyg editor also uses a div) and the append function it's not working. We check in the console, and the string we are trying to append is there, also jquery grabs the element (also checked in the console log) but the append function it's not working.
PD: I apologize for my english
The html
<div data-ng-controller="PreviewCtrl">
<div class="container">
<div id="resumenPreview"></div>
</div>
</div>
The controller
angular.module('module').controller('PreviewCtrl', ['$scope', '$routeParams', '$location', '$http', 'selectedElement',
function ($scope, $routeParams, $location, $http, selectedElement) {
$scope.id = $routeParams.id;
$scope.mensaje = $scope.id;
$scope.imagen = null;
$scope.dataImagen = null;
//is not working either
$('#resumenPreview').append("hola");
$scope.pageLoad = function () {
var x = selectedElement.data.Resumen;
//This is properly displayed in the console
console.log(x);
//This too, is displayed in the console log
console.log($('#resumenPreview'));
// Why this isn't working? I'am clueless
$('#resumenPreview').append(x);
};
$scope.pageLoad();
}]);
My guess would be there are multiple divs with id="resumenPreview". But this is clearly the wrong way to handle such things in angular. There shouldn't be dom-manipulation in the controller - directives should take care of dom-related stuff. Put the html-string into the scope and let angular handle the injection into the dom:
instead of $('#resumenPreview').append(x); do $scope.resumenPreview = x;
and in the template do this:
<div class="container">
<div ng-bind-html="resumenPreview"></div>
</div>
Solve it with angularjs for the ng-bind-html to work it's necessary to include
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-sanitize.js"></script>
and to add 'ngSanitize' as a dependency in the app module configuration. And then just do what #Johannes Reuter posted.
Thanks everybody, Greetings.

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