Complete rendering page first before executing a function in angularJS - html

I have this code in javascript
$scope.sample = function(){
console.log(document.getElementById('foo'+modelId));
}
which returns false due to the HTML not yet complete rendering the page. See below:
<li ng-repeat="item in items" >
<input ng-model='foo'{{item.modelId}}
</li>
I want to avoid using timeout, is there a way to assure the HTML is completely rendered before executing the code.

I think that the best way is to listen to scope.$last event and than run any code you need.
Here is an example:
angular.module('myApp', [])
.directive('repeatFinished', function() {
return function(scope, element, attrs) {
if (scope.$last) { // Here we can see that all ng-repeat items rendered
scope.$eval(attrs.repeatFinished);
}
}
});
And than on your html you simple add:
<li ng-repeat="item in items" repeat-finished="sample()">
//....
</li>

Related

AngularJS directive - access element's dataset

Here is my simplified template:
<div>
<img ng-click="addSubPlots($event)"
data-status="add"
src="abc.svg" />
</div>
And here is a directive that loads that template:
a.directive("trendChartToolbar", function ($templateRequest, $compile) {
return {
link: function (scope, elem, attrs) {
$templateRequest('template.html').then(function (html) {
var template = angular.element(html);
$(elem).append(template);
template = $compile(template)(scope);
});
}
};
});
My expectation was that I would be able to access template's dataset and modify the 'status' key. But when I check it the dataset is empty. I know that Angular removes 'data-' but I also dont see any 'status' anywhere. Any idea how to make something like this working? The reason I am trying this is when I click on a button I need to get button's status. Here is code I am using in the controller:
$scope.addSubPlots = function(event){
console.log(event.target.dataset.status);
}
Please share some ideas.
Thanks

Pass element using ng-show AngularJS

HTML
<li ng-show="sample($event)" TestLi</li>
Javascript
$scope.sample = function($event){ //$event is undefined
//do something
}
I've only tried passing the html element using ng-click but is there a way to pass it using ng-show?.
The attribute ng-show, ng-hide and ng-if usually evaluate expression and not function. You can read about it here:
https://docs.angularjs.org/api/ng/directive/ngShow
However, if you really wish to get the target element, you may try writing a very simple directive.
<li ng-show="sample($event)" getTarget> TestLi</li>
app.directive("getTarget", function() {
return {
link: function(scope, element, attrs) {
console.log(element);
}
}
});

How to create a separate scope isolated from ng-repeat in Angular?

I am new to AngularJS and have some trouble understanding the concept of scope in Angular. I have read some posts on stackoverflow as well as online articles, which advise me to create a custom directive to create an isolate scope, but I am getting nowhere...
As for the project I'm working on, I am trying to make a button that when clicked, will trigger a textarea. However, because of ng-repeat, the textarea is triggered for all buttons while I click only one.
My .js file:
angular.module('myApp')
.controller('myCtrl', function ($scope, Question) {
scope.visible = false;
scope.toggle = function() {
scope.visible = !scope.visible;
};
.directive("myDirective", function () {
return {
scope: {
ngClick: '&',
ngShow: '&'
}
}
});
Here is my HTML file:
<ul>
<li ng-repeat="object in objectList">
<button type="text" myDirective ng-click="toggle()">Click</button>
<textarea myDirective ng-show="visible"></textarea>
</li>
</ul>
Angular is creating child (NOT isolated) scope when ng-repeating, try this out, when you ng-init a variable, it is only visible within that repeat div.
<div ng-repeat="i in [0,1,2,3,4,5,6,7,8,9]" ng-init="visible=false">
<button ng-click="visible=!visible">Toggle</button>
<h1 ng-show="visible">look at me!</h1>
</div>
Plunker
There is no need to use a directive. You need to use object in the foreach to refer each item in the loop.
Add visible to each object in objectList:
$scope.objectList = [
{ visible: false },
{ visible: false },
{ visible: false }
];
Then the toggle button will need to pass the object to toggle:
$scope.toggle = function (object) {
object.visible = !object.visible;
};
The ng-show will need to check object.visible and ng-click will need to pass the object:
<button type="text" ng-click="toggle(object)">Click</button>
<textarea ng-show="object.visible"></textarea>
Plunkr

Compiling dynamic HTML strings from database

The Situation
Nested within our Angular app is a directive called Page, backed by a controller, which contains a div with an ng-bind-html-unsafe attribute. This is assigned to a $scope var called 'pageContent'. This var gets assigned dynamically generated HTML from a database. When the user flips to the next page, a called to the DB is made, and the pageContent var is set to this new HTML, which gets rendered onscreen through ng-bind-html-unsafe. Here's the code:
Page directive
angular.module('myApp.directives')
.directive('myPage', function ($compile) {
return {
templateUrl: 'page.html',
restrict: 'E',
compile: function compile(element, attrs, transclude) {
// does nothing currently
return {
pre: function preLink(scope, element, attrs, controller) {
// does nothing currently
},
post: function postLink(scope, element, attrs, controller) {
// does nothing currently
}
}
}
};
});
Page directive's template ("page.html" from the templateUrl property above)
<div ng-controller="PageCtrl" >
...
<!-- dynamic page content written into the div below -->
<div ng-bind-html-unsafe="pageContent" >
...
</div>
Page controller
angular.module('myApp')
.controller('PageCtrl', function ($scope) {
$scope.pageContent = '';
$scope.$on( "receivedPageContent", function(event, args) {
console.log( 'new page content received after DB call' );
$scope.pageContent = args.htmlStrFromDB;
});
});
That works. We see the page's HTML from the DB rendered nicely in the browser. When the user flips to the next page, we see the next page's content, and so on. So far so good.
The Problem
The problem here is that we want to have interactive content inside of a page's content. For instance, the HTML may contain a thumbnail image where, when the user clicks on it, Angular should do something awesome, such as displaying a pop-up modal window. I've placed Angular method calls (ng-click) in the HTML strings in our database, but of course Angular isn't going to recognize either method calls or directives unless it somehow parses the HTML string, recognizes them and compiles them.
In our DB
Content for Page 1:
<p>Here's a cool pic of a lion. <img src="lion.png" ng-click="doSomethingAwesone('lion', 'showImage')" > Click on him to see a large image.</p>
Content for Page 2:
<p>Here's a snake. <img src="snake.png" ng-click="doSomethingAwesone('snake', 'playSound')" >Click to make him hiss.</p>
Back in the Page controller, we then add the corresponding $scope function:
Page controller
$scope.doSomethingAwesome = function( id, action ) {
console.log( "Going to do " + action + " with "+ id );
}
I can't figure out how to call that 'doSomethingAwesome' method from within the HTML string from the DB. I realize Angular has to parse the HTML string somehow, but how? I've read vague mumblings about the $compile service, and copied and pasted some examples, but nothing works. Also, most examples show dynamic content only getting set during the linking phase of the directive. We would want Page to stay alive throughout the life of the app. It constantly receives, compiles and displays new content as the user flips through pages.
In an abstract sense, I guess you could say we are trying to dynamically nest chunks of Angular within an Angular app, and need to be able to swap them in and out.
I've read various bits of Angular documentation multiple times, as well as all sorts of blog posts, and JS Fiddled with people's code. I don't know whether I'm completely misunderstanding Angular, or just missing something simple, or maybe I'm slow. In any case, I could use some advice.
ng-bind-html-unsafe only renders the content as HTML. It doesn't bind Angular scope to the resulted DOM. You have to use $compile service for that purpose. I created this plunker to demonstrate how to use $compile to create a directive rendering dynamic HTML entered by users and binding to the controller's scope. The source is posted below.
demo.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
</body>
</html>
script.js
var app = angular.module('app', []);
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Found in a google discussion group. Works for me.
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$compile(element)($rootScope);
});
You can use
ng-bind-html https://docs.angularjs.org/api/ng/service/$sce
directive to bind html dynamically.
However you have to get the data via $sce service.
Please see the live demo at http://plnkr.co/edit/k4s3Bx
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.getHtml=function(){
return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
}
});
<body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
</body>
Try this below code for binding html through attr
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic);
than element.html(attr.dynamic);

Executing view-specific javascript when the view is updated

I've been trying to find out how to execute some view-specific javascript code when the model has changed. In the example below, whenever you click the "Say"-button, a new entry will be added to the model, updating the entries-list. The stylesheet limits the entries-list's height to about five entries.
What is the correct way to call something like scrollLastChatEntryElementIntoView();? I know how to scroll elements into view, but I can't seem to find any info on how and when I should do this in response to the view being updated? Where am I supposed to declare the script, and when am I supposed to call it?
<div class="chat">
<ol class="entries">
<li class="entry" ng-repeat="entry in chat.entries">
<label>{{entry.sender}}</label> {{entry.text}}
</li>
</ol>
<form class="newEntry" ng-submit="chat.newEntry.submit()">
<input class="text" ng-model="chat.newEntry.text" placeholder="Type to chat"/>
<span class="button submit" ng-click="chat.newEntry.submit()">Say</span>
</form>
</div>
I had a similar situation recently and the way I did it was to create a "auto-scrolling" directive that is listening for the 'DOMSubtreeModified' event on the list element and automatically scrolls down when a new element is added to it.
app.directive('autoScrolling', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var el = angular.element(element);
scope.scrollDown = function(evt) {
// scroll down:
el.scrollTop(el.prop('scrollHeight'));
};
scope.scrollDown();
// each time the DOM element of the list changes,
// make sure we are scrolled all the way down...
element.bind('DOMSubtreeModified', scope.scrollDown);
}
};
});
and then on your list element
<ol auto-scrolling>...
plnkr demo here