How to dynamically call a html page - angularjs

I currently ng-include an html doc.
<div ng-include="'templates/calendar.html'"></div>
behind the scenes, this document loops through a javascript object to create the calendar. However, I plan to have updates to that object and I'd like to set up a click event to re-load calendar.html using the updated object. How can I do this?

You can create a directive and give it the calendar template to show.
Your directive will get some data (which you want to display) in a scope. Use your scope data to populate the template. Then, when your data changes, replace the data in the scope and the view will change itself accordingly.
You won't need to reload the template.
Update:
Try this code in jsfiddle to see the demonstration of the concept:
<div ng-app="Demo" ng-controller="ChildCtrl">
<iso-element></iso-element>
</div>
Js part:
angular.module("Demo", [])
.controller("ChildCtrl", function($rootScope, $scope, $interval) {
var flipWording = function () {
if ($scope.data === 'Hello Galaxy') {
$scope.data = 'Hello World';
} else {
$scope.data = 'Hello Galaxy';
}
};
$scope.data = "Hello World";
$interval(function () {
flipWording();
}, 2000);
})
.directive("isoElement", function() {
return {
restrict: "E",
template: '<p>{{data}}</p>', // You can give a path here as well like abc/foo.html
scope: true,
link: function(scope) {
}
};
});
Because the scope data gets flipped the directive shows updated value every time.

Related

angular.js - passing an object from directive to the view controller

*Please note: there is a Plunker link:
https://plnkr.co/edit/PAINmQUHSjgPTkXoYAxf?p=preview
At first I wanted to pass an object as parameter on directive click event,
(it was too complex for me), so i decide to simplify it by sending the event and the object separately.
In my program the object is always undefined in the view-controller and the view itself in oppose to the Plunker example.
In the Plunker example it's undefined on the controller only on the first passing event (the second directive click event works fine).
I don't know why I get 2 different results in the simple Plunker simulation and my massive code, I hope both cases are 2 different results of the same logic issue.
A solution with passing an object as parameter from directive by event function will be welcome as well.
HTML
<pick-er get-obj-d="getObj()" obj-d="obj"></pick-er>
View-Controller
function mainController($scope)
{
$scope.test = "work";
$scope.getObj = function(){
$scope.test = $scope.obj;
}
}
Directive:
function PickerDirective()
{
return {
restrict: 'E',
scope: // isolated scope
{
obj : '=objD',
getObj: '&getObjD'
},
controller: DirectiveController,
template:`<div ng-repeat="item in many">
<button ng-click="sendObj()">
Click on me to send Object {{item.num}}
</button>
</div>`
};
function DirectiveController($scope, $element)
{
$scope.many =[{"num":1,}];
$scope.sendObj = function() {
$scope.obj = {"a":1,"b":2, "c":3};
$scope.getObj();
}
}
}
I your case, will be more simple to use events, take a look at this Plunker:
https://plnkr.co/edit/bFYDfhTqaUo8xhzSz0qH?p=preview
Main controller
function mainController($scope)
{
console.log("mainCTRL ran")
$scope.test = "work";
$scope.$on('newObj', function (event, obj) {
$scope.obj = obj;
$scope.test = obj;
});
}
Directive controller
function DirectiveController($scope, $element)
{
$scope.many =[{"num":1,}]
$scope.sendObj = function() {
$scope.$emit('newObj', {"a":1,"b":2, "c":3} )
}
}
return {
restrict: 'E',
controller: DirectiveController,
template:'<div ng-repeat="item in many"><button ng-click="sendObj()">Click on me to send Object {{item.num}}</button></div>'
}

Angular - changes to directive controller's scope aren't reflected in view

Changes to my scope variable foo are getting updated in the html. When that value is change inside the scope of a directive's controller, it isn't updating in the html.
What do I need to do to make it update?
I have a simple example:
app.js
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.foo = 99;
$scope.changeValue = function() {
$scope.foo = $scope.foo + 1;
}
});
app.directive('d1', function(){
return {
restrict: 'E',
scope: {
theFoo: '='
},
templateUrl: 'd1.html',
controller: 'd1Ctrl',
}
});
app.controller('d1Ctrl', function($scope) {
$scope.test = $scope.theFoo;
});
d1.html
<div>
<p>The value of foo is '{{theFoo}}'.</p>
<p>The value of test is '{{test}}'.</p>
</div>
inside index.html
<d1 the-foo='foo'>
</d1>
<button ng-click='changeValue()'>change value</button>
So in summary, {{theFoo}} is updating, but {{test}} isn't. Why?
The reason is that $scope.foo value is a primitive.
In the directive controller you only assign $scope.test once when controller initializes. Primitives have no inheritance the way objects do so there is nothing that would change $scope.test after that initial assignment
If you used an object instead to pass in ... inheritance would be in effect and you would see changes...otherwise you would need to watch $scope.theFoo and do updates to $scope.test yourself
The code you have in your controller only initializes to that value if it is indeed set at the time the controller is linked. Any subsequent changes are not going to work.
If you want to bind any subsequent changes, then you need to set a $watch statement either in your controller or a link function.
$scope.$watch( 'theFoo', function(val){ $scope.test = val; })
updated plunker - http://plnkr.co/edit/eWoPutIJrwxZj9XJu6QG?p=preview
here you have isolated the scope of the directive, so test is not visible to the d1.html, if you need to change test along with the theFoo you must first make it visible to the directive by
app.directive('d1', function(){
return {
restrict: 'E',
scope: {
theFoo: '=',
test : '=' //getting test as well
},
templateUrl: 'd1.html',
controller: 'd1Ctrl',
}
});
and in index.html you should pass the value to the test by
<d1 the-foo='foo' test='foo'></d1>
in the above code your controller is not much of a use , code will work fine even without this part controller: 'd1Ctrl'.
with this example you dont have to use $watch.

Angularjs update controller variable from directive and use in view

I've just started to use Angularjs and with the help of some stackoverflow answers I have created an image fallback directive with Angularjs.
The fallback functionality is working, but now I would like the use a boolean, a variable set in the controller I guess, in combination with ng-show in the view which indicates if the fallback image is used, or if the original image is loaded. I've changed my code several times, but it never worked....
(The teamCtrl is a seperated controller which does work and can be ignored in this issue, so I did not include the code.)
This is a piece of my html:
<div class="thumbnail margin-bot-20px">
<img ng-src="../img/team{{teamCtrl.selectedteam.id}}.jpg" myfallback-src="../img/onbekend.jpg" />
</div>
<div ng-controller="fallbackController as fbCtrl">
<p>
Wijzig foto
Verwijder foto
</p>
</div>
This is the directive and the directive's controller:
(function () {
'use strict';
angular.module('PD.fallback', [])
.directive('myfallbackSrc', myfallbackSrc);
angular.module('PD.fallback')
.controller('fallbackController', fallbackController);
function fallbackController()
{
this.directivedummy = false;
};
function myfallbackSrc()
{
var directive = {
link: link
//controller: fallbackController, // controllerfunctie
//controllerAs: 'vm' // controllerAs-alias
//bindToController: true
//scope: {}
};
return directive;
};
// 3. Link-function implementeren
function link(scope, element, attrs)
{
element.bind('error', function()
{
scope.directivedummy = false;
if (attrs.src != attrs.myfallbackSrc)
attrs.$set('src', attrs.myfallbackSrc);
});
element.bind('load', function()
{
if (attrs.src != attrs.myfallbackSrc)
scope.directivedummy = true;
});
}
})();
So I would like to show/hide a button in the view html. The button must be visible when the src image was loaded successfully and must be hidden when the fallback image is loaded.
Hopefully someone can help me?
Assuming your are not using ControllerAs syntax, you need to trigger the $digest since the bind callback is happening outside of Angular
element.bind('error', function(){
scope.$apply(function (){
scope.directivedummy = false;
if (attrs.src != attrs.myfallbackSrc)
attrs.$set('src', attrs.myfallbackSrc);
});
});

service only works after `$rootScope.$appy()` applied

I am loading the template from angular-service but that's not updating the template unless i use the $rootScope.$appy(). but my question is, doing this way this the correct approach to update the templates?
here is my code :
var app = angular.module('plunker', []);
app.service('modalService', function( $rootScope ) {
this.hide = function () {
this.show = false;
}
this.showIt = function () {
this.show = true;
}
this.setCategory = function ( category ) {
return this.showPath = category+'.html'
}
this.showCategory = function (category) {
this.setCategory( category )
$rootScope.$apply(); //is this correct?
}
})
app.controller('header', function($scope) {
$scope.view = "home view";
});
app.controller('home', function($scope, modalService) {
$scope.name = 'World';
$scope.service = modalService;
});
//header directive
app.directive('headerDir', function( modalService) {
return {
restrict : "E",
replace:true,
templateUrl:'header.html',
scope:{},
link : function (scope, element, attrs) {
element.on('click', '.edit', function () {
modalService.showIt();
modalService.showCategory('edit');
});
element.on('click', '.service', function () {
modalService.showIt();
modalService.showCategory('service');
})
}
}
});
app.directive('popUpDir', function () {
return {
replace:true,
restrict:"E",
templateUrl : "popup.html"
}
})
Any one please advice me if i am wrong here? or can any one show me the correct way to do this?
click on links on top to get appropriate template to load. and click on the background screen to close.
Live Demo
If you don't use Angular's error handling, and you know your changes shouldn't propagate to any other scopes (root, controllers or directives), and you need to optimize for performance, you could call $digest on specifically your controller's $scope. This way the dirty-checking doesn't propagate. Otherwise, if you don't want errors to be caught by Angular, but need the dirty-checking to propagate to other controllers/directives/rootScope, you can, instead of wrapping with $apply, just calling $rootScope.$apply() after you made your changes.
Refer this link also Angular - Websocket and $rootScope.apply()
Use ng-click for handling the click events.
Template:
<div ng-repeat="item in items">
<div ng-click="showEdit(item)">Edit</div>
<div ng-click="delete(item)">Edit</div>
</div>
Controller:
....
$scope.showEdit = function(item){
....
}
$scope.delete = function(item){
....
}
If you use jquery or any other external library and modify the $scope, angular has no way of knowing if something has changed. Instead if you use ng-click, you let angular track/detect change after you ng-click handler completes.
Also it is the angular way of doing it. Use jquery only if there is no other way to save the world.

AngularJS - Passing Scope between directives

In the interest of abstraction, I'm trying to pass a scope between directives with little success... Basically, this is a modal type scenario:
Directive A - handles click function of on screen element:
.directive('myElement', ['pane', function(pane){
return {
restrict: 'A',
scope: {},
link: function(scope,elem,attrs){
//im going to try and call the form.cancel function from a template compiled in another directive
scope.form = {
cancel: function(){
pane.close();
}
};
scope.$watch(function(){
var w = elem.parent()[0].clientWidth;
elem.css('height',(w*5)/4+'px');
});
elem.on('click', function(){
//this calls my service which communicates with my other directive to 1) display the pane, and 2) pass a template compiled with this directive's scope
pane.open({
templateUrl: 'views/forms/edit.html',
scope: scope //I pass the scope to the service API here
});
});
}
}
}])
I have a service called 'Pane' to handle the API:
.service('pane',['$rootScope', function($rootScope){
var open = function(data){
$rootScope.$broadcast('openPane',data); //this broadcasts my call to open the pane with the template url and the scope object
};
var close = function(){
$rootScope.$broadcast('closePane');
};
return {
open: open,
close: close
}
}]);
Finally, directive B is lying in wait for the 'openPane' broadcast which includes the template url and the scope:
.directive('pane',['$compile','$templateRequest','$rootScope', function($compile,$templateRequest,$rootScope){
return {
restrict: 'A',
link: function(scope,elem,attrs){
var t;
scope.$on('openPane', function(e,data){ //broadcast is received and pane is displayed with template that gets retrieved
if(data.templateUrl){
$templateRequest(data.templateUrl).then(function(template){
//this is where the problem seems to be. it works just fine, and the data.scope object does include my form object, but calling it from the template that opens does nothing
t = $compile(template)(data.scope);
elem.addClass('open');
elem.append(t);
}, function(err){
console.log(JSON.stringify(err));
});
}
else if(data.template){
t = $compile(angular.element(data.template))(data.scope);
elem.addClass('open');
elem.append(t);
}
else console.log("Can't open pane. No templateUrl or template was specified.")
});
scope.$on('closePane', function(e,data){
elem.removeClass('open');
t.remove();
});
}
}
}])
The problem is that when the last directive, 'pane', receives the 'openPane' broadcast, it opens and appends the template just fine, but when i call the function 'form.cancel()' defined in my original directive like so:
<button type="button" ng-click="form.cancel()">Cancel</button>
... nothing happens. Truth is, I'm not sure what I'm doing is legit at all, but i want to understand why it isn't working. The ultimate goal here is to be able to pass the scope of one directive, along with a form template, to the Pane directive, so all my forms (which are controlled by their own directives) can be 'injected' into the pane.
Without a running example I'm suspecting the likely cause to be the scope of your scope when passed to your pane template. The scope itself does get passed and used when you compile your pane template, but its closure is lost along the way, so you likely can't see pane service which is part of the directive factory closure and form.cancel uses.
I've written a simplified example that does work and doesn't rely on closures bt rather on local variables. You could accomplish a similar thing if you called .bind(pane) on your scope.form.cancel function and within replace pane by this.
So here's a working example and this is its code:
/* ************ */
/* Pane service */
class PaneService {
constructor($rootScope) {
console.log('pane service instantiated.', this);
this.$rootScope = $rootScope;
}
open(template, scope) {
this.$rootScope.$emit('OpenPane', template, scope);
}
close(message) {
this.$rootScope.$emit('ClosePane', message);
}
}
PaneService.$inject = ['$rootScope'];
/* ************************* */
/* Pane directive controller */
class PaneController {
constructor($rootScope, $compile, $element) {
console.log('pane directive instantiated.', this);
this.$compile = $compile;
this.$element = $element;
$rootScope.$on('OpenPane', this.open.bind(this));
$rootScope.$on('ClosePane', this.close.bind(this));
}
open(event, template, scope) {
console.log('pane directive opening', template, scope);
var t = this.$compile(template)(scope);
this.$element.empty().append(t);
}
close(evet, message) {
console.log('pane directive closing', message);
this.$element.empty().append('<strong>' + message + '</strong>');
}
}
PaneController.$inject = ['$rootScope', '$compile', '$element'];
var PaneDirective = {
restrict: 'A',
controller: PaneController,
controllerAs: 'pane',
bindToController: true
}
/* *************** */
/* Page controller */
class PageController {
constructor(paneService, $scope) {
console.log('page controller instantiated.', this);
this.paneService = paneService;
this.$scope = $scope;
}
open() {
console.log('page controller open', this);
this.paneService.open('<button ng-click="page.close(\'Closed from pane\')">Close from pane</button>', this.$scope);
}
close(message) {
console.log('page controller close');
this.paneService.close(message);
}
}
PageController.$inject = ['paneService', '$scope'];
angular
.module('App', [])
.service('paneService', PaneService)
.directive('pane', () => PaneDirective)
.controller('PageController', PageController);
And page template is very simple:
<body ng-app="App">
<h1>Hello Plunker!</h1>
<div ng-controller="PageController as page">
<button ng-click="page.open()">Open pane</button>
<button ng-click="page.close('Closed from page')">Close pane</button>
</div>
<div pane></div>
</body>

Resources