Integration of power bi reports with angular js in mvc application - angularjs

How we can integrate power BI report with angular JS in mvc existing application. AS of now I am facing issue to display power bi report on angular view.

The way to go is: Use PowerBI Embedded (https://azure.microsoft.com/en-us/services/power-bi-embedded/)
I'm not an angular expert, but there is a Github repo aimed at this: https://github.com/Microsoft/PowerBI-Angular

Check out http://plnkr.co/edit/tQc1DF?p=info for a basic example of embedding a powerbi report and doing page navigation, using angular 1.4.x
var app = angular.module('plunker', [
'powerbi'
]);
app.controller('MainCtrl', function($scope, $http, models, PowerBiService) {
var staticReportUrl = 'https://powerbiembedapi.azurewebsites.net/api/reports/c52af8ab-0468-4165-92af-dc39858d66ad';
var _filterPaneEnabled = false;
var _navContentPaneEnabled = false;
var _reportHandle = null;
$scope.tree = [];
$http.get(staticReportUrl)
.then(function(responce) {
//create the config for the directive
var config = angular.extend(responce.data, {
settings: {
filterPaneEnabled: _filterPaneEnabled,
navContentPaneEnabled: _navContentPaneEnabled
}
});
$scope.embedConfiguration = config;
//create the nav-tree
$scope.tree.push(new models.Node(responce.data));
}, function(reason) {
});
$scope.onEmbedded = function(report) {
// get a reference to report object
_reportHandle = report;
//attach to events
report.on('loaded', OnloadedReport);
report.on('error', OnErrorReport);
};
function OnloadedReport(c) {
//get available pages to attach to navigation tree
_reportHandle.getPages()
.then(function(pages) {
pages.forEach(function(page) {
$scope.$apply(function() {
//populate the nav-tree
$scope.tree[0].pages.push(new models.Leaf(page));
});
});
})
.catch(function(error) {
console.log(error);
});
}
function OnErrorReport(e) {
console.log(e);
}
$scope.toggleFilterPaneClicked = function() {
_filterPaneEnabled = !_filterPaneEnabled;
_reportHandle.updateSettings({
filterPaneEnabled: _filterPaneEnabled
});
};
$scope.toggleNavContentPaneClicked = function() {
_navContentPaneEnabled = !_navContentPaneEnabled;
_reportHandle.updateSettings({
navContentPaneEnabled: _navContentPaneEnabled
});
};
$scope.setPage = function(page) {
_reportHandle.setPage(page.name);
};
$scope.fullScreen = function() {
_reportHandle.fullscreen();
};
});
app.factory('models', function() {
var Node = function(dataset) {
var self = this;
self.id = dataset.id;
self.name = dataset.name;
self.type = dataset.type;
self.accessToken = dataset.accessToken;
self.embedUrl = dataset.embedUrl;
self.webUrl = dataset.webUrl;
self.pages = [];
return self;
};
var Leaf = function(page) {
var self = this;
self.name = page.name;
self.displayName = page.displayName;
return self;
};
return {
Node: Node,
Leaf: Leaf
};
})
[1]https://microsoft.github.io/PowerBI-JavaScript/demo/static.html

Related

Where to handle returning data from Angular service?

I try to handle an Angularjs 1 project by using classes, I have created class as the following
angular.module('Models').factory('Project', function (API, $rootScope) {
var Project = function() {
return new Project.fn.init();
}
// instance methods
Project.fn = Project.prototype = {
init: function() {
this.id = null,
this.name = ""
},
setId: function(id) {
this.id = id;
},
setName: function(name) {
this.name = name;
},...
Now I set the obj attr. in the same class as following:
Project.getAll = function(scopeProjects) {
return API.getAll(this).then(function(response) {
var allProjects = response.data.body;
allProjects.forEach(function (project) {
var obj = new Project();
obj.setId(project.id);
obj.setName(project.name);
scopeProjects.push(obj);
})
}, function(error) {
console.log("Fail : ", error);
});
}
my question is where to use my setters?
Do I have to handle this by returning the data to controllers or the way I use here is the best one?

How to mock $window.Notification

I am still learning the ropes when it comes to unit testing with angular. I have an angular service that I use to create HTML5 notifications. Code is similar to the following:
(function() {
'use strict';
angular
.module('blah')
.factory('OffPageNotification', offPageNotificationFactory);
function offPageNotificationFactory($window) {
//Request permission for HTML5 notifications as soon as we can
if($window.Notification && $window.Notification.permission !== 'denied') {
$window.Notification.requestPermission(function (status) { });
}
function OffPageNotification () {
var self = Object.create(OffPageNotification.prototype);
self.visibleNotification = null;
return self;
}
OffPageNotification.prototype.startNotification = function (options) {
var self = this;
self.options = options;
if(self.options.showHtml5Notification && (!self.options.onlyShowIfPageIsHidden || $window.document.hidden)) {
if($window.Notification && $window.Notification.permission !== 'denied') {
self.visibleNotification = new $window.Notification('Notification', {
body: self.options.notificationText,
icon: self.options.notificationIcon
});
}
}
};
.
.
.
return new OffPageNotification();
}
})();
I am attempting to write unit tests for this but am unsure how to mock $window.Notification so it can be used as both a constructor...
self.visibleNotification = new $window.Notification(....)
and also contain properties
if($window.Notification && $window.Notification.permission !== 'denied')
and methods....
$window.Notification.requestPermission(
An example of something I have tried is:
describe('startNotification', function() {
beforeEach(function() {
var mockNotification = function (title, options) {
this.title = title;
this.options = options;
this.requestPermission = sinon.stub();
};
mockNotification.prototype.permission = 'granted';
mockWindow = {
Notification: new mockNotification('blah', {}),
document: {hidden: true}
};
inject(function (_OffPageNotification_) {
OffPageNotification = _OffPageNotification_;
});
});
it('should display a html5 notification if the relevant value is true in the options, and permission has been granted', function(){
var options = {
showHtml5Notification: true,
onlyShowIfPageIsHidden: true
};
OffPageNotification.startNotification(options);
});
});
I get an error saying '$window.Notification is not a constructor' with this setup and I understand why (I am passing in an instantiated version of the mockNotification). But if I set mockWindow.Notification = mockNotification then I get an error when it calls requestPermission since this is undefined.
Any help is appreciated
Notification should be a constructor. And it should have static properties and methods.
All of the relevant properties of mockNotification are instance properties, while they should be static:
function MockNotification() {}
MockNotification.title = title;
MockNotification.options = options;
MockNotification.requestPermission = sinon.stub();
mockWindow = {
Notification: MockNotification,
document: {hidden: true}
};

Two $firebaseArrays on one page & one ctrl

I would like to use two different $firebaseArrays on one view with one controller. But only one of them works and the other only works if i put him in his own controller.
from my factory file:
.factory("AlphaFactory", ["$firebaseArray",
function($firebaseArray) {
var ref = firebase.database().ref('alpha/');
return $firebaseArray(ref);
}
])
.factory("BetaFactory", ["$firebaseArray",
function($firebaseArray) {
var ref = firebase.database().ref('beta/');
return $firebaseArray(ref);
}
])
and my controller:
.controller('DemoCtrl', function($scope, AlphaFactory, BetaFactory) {
$scope.alphaJobs = AlphaFactory;
$scope.addalphaJob = function() {
$scope.alphaJobs.$add({
Testentry: $scope.loremipsum,
timestamp: Date()
});
$scope.alphaJob = "";
};
$scope.betaJobs = BetaFactory;
$scope.addbetaJob = function() {
$scope.betaJobs.$add({
Testentry2: $scope.dolorest,
timestamp: Date()
});
$scope.betaJob = "";
};
)}
Are you sure it is not a simple matter of a promise has not finished?
var alphaJobs = AlphaFactory;
alphaJobs.$loaded().then(function() {
// Do something with data if needed
$scope.alphaJobs = alphaJobs;
});
var betaJobs = BetaFactory;
betaJobs.$loaded().then(function() {
// Do something with data if needed
$scope.betaJobs = betaJobs;
});

Uploading images to Firebase with AngularJS

I have a service that handles "episodes": creating, deleting and updating them. It looks like this:
app.service('Episode', ['$firebase', 'FIREBASE_URL', function($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var episodes = $firebase(ref);
return {
all: episodes,
create: function(episode) {
location.reload();
//Add to firebase db
return episodes.$add(episode);
},
delete: function(episodeId) {
location.reload();
return episodes.$remove(episodeId);
},
update: function(episode) {
location.reload();
return episodes.$save(episode);
}
};
}]);
Inside my controller:
app.controller('AdminCtrl', ['$scope', 'Episode', function ($scope, Episode) {
$scope.episodes = Episode.all;
$scope.createEpisode = function(){
Episode.create($scope.episode).then(function(data){
$scope.episode.name = '';
$scope.episode.title = '';
$scope.episode.description = '';
$scope.episode.time = '';
$scope.episode.img = '';
});
};
$scope.deleteEpisode = function(episodeId){
if(confirm('Are you sure you want to delete this episode?') === true) {
Episode.delete(episodeId).then(function(data){
console.log('Episode successfully deleted!');
});
}
};
$scope.updateEpisode = function(episode) {
Episode.update($scope.episode).then(function(data) {
console.log('Episode successfully updated.');
});
};
The only example of uploading images to Firebase from AngularJS I've seen online is this: https://github.com/firebase/firepano
How am I able to incorporate this into an object based addition/update instead of finding it's index/link?

AngularJS local storage - initialize app retrieving local-stored data

I'm pretty new to angular and I'm trying to avoid losing items added on a simple cart application when the user refreshes the page.
I'm using angularLocalStorage (https://github.com/agrublev/angularLocalStorage) but don't know how to retrieve it back the content.
My lines:
var myApp = angular.module('ionicApp', ['ionic','angularLocalStorage']);
myApp.factory('prodottiData', function($http) {
return {
getFooOldSchool: function(callback) {
$http.get('http://192.168.1.128/hongkongapp/?json=get_recent_posts&post_type=product&custom_fields=all').success(callback);
}
}
});
myApp.factory('DataService', function() {
var myCart = new shoppingCart("AngularStore");
return {
cart : myCart
};
});
myApp.controller('MyController', function MyController ($scope, storage, $ionicSideMenuDelegate, prodottiData, DataService, $sce) {
$scope.toggleLeft = function() {
$ionicSideMenuDelegate.$getByHandle('mainMenu').toggleLeft();
};
$scope.toggleMySecondMenuLeft = function() {
$ionicSideMenuDelegate.$getByHandle('mySecondMenu').toggleLeft();
};
//adding menu data to the scope object
prodottiData.getFooOldSchool(function(data) {
$scope.menu = data;
});
//adding the cart to the scope object
$scope.cart = DataService.cart;
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
images = $scope.menu;
$scope.showloader = function(){
$scope.shownImage = this.post.thumbnail_images.full.url;
$scope.itemDesc = this.post.content;
$scope.itemPrice = this.post.custom_fields._price[0];
$scope.productName = this.post.title;
$scope.skuProdotto = this.post.id;
}
});
Now, if I check local storage on the console I can see something is really stored, but I miss the way to re-populate the cart at startup.
Any help would be great!
why not just using browser local storage ?
you can add it to your services.js as a new service and just used that.
var storeService = myAppServices.factory('storeService', function() {
var service =
{
setClientData:function(client_details)
{
window.localStorage.setItem( "client_data", JSON.stringify(client_details) );
client_data = client_details;
},
getClientData:function()
{
if (client_data == null)
{
client_data = JSON.parse(window.localStorage.getItem("client_data"));
}
return client_data;
}
}
var client_data = null;
return service;
});
From the documentation, to retrieve, it's storage.get('key')
So, to check after refresh:
if (storage.get('someKey')){
$scope.retrieved_value = storage.get('someKey');
}else{
// whatever
}
You can use localStorage instead windows.localStorage.
if(typeof(Storage)!=="undefined")
{
// Code for localStorage/sessionStorage.
var hello = "Hello World!!";
localStorage.setItem("hello",hello);
// get string
console.log(localStorage.getItem("hello")); // will return 'Hello World!!'
var me = {name:'abel',age:26,gender:'male'};
localStorage.setItem("user", JSON.stringify(me));
//fetch object
console.log(localStorage.getItem("user")); // will return {"name":"myname","age":99,"gender":"myGender"}
var objetos = JSON.parse(localStorage.getItem("user"));
console.log(objetos.name);
}
else
{
// Sorry! No Web Storage support..
}

Resources