Angular: ng-repeat calculate data in view - javascript

I am writing an angular website, but I have the following problem. I have 2 data arrays that I get from my json files.
I use an ng-repeat to go over my projects in my html file, and I use another ng-repeat to go over my projects.languages.
Now what I want to do is to make it that for every language I find I am going to search in the languages data
and get the other information.
How can I easly get the language in the ng-repeat, I need to also calculate in that the data maybe not avaible yet,
because I get the json data async.
This is the code I have right now:
<div class="container-fluid contentcontainer">
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<div class="languageoverlay">
<span ng-repeat="language in projects[$index].languages">
<img ng-src="img/languages/android.png" ng-alt="{{language}}" />
<font ng-show="!$last">+</font>
</span>
</div>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
</div>
<!--this is just to try, don't need to use this-->
<h1>{{getLanguage("CSharp")}}</h1>
App.js
app.service('projectService', ['$http', '$q', function($http, $q) {
var projectsDeferred = $q.defer();
var languagesDeferred = $q.defer();
$http({
method: 'POST',
url: 'json/projects.json',
cache: true
}).then(function(data) {
projectsDeferred.resolve(data.data.projects);
});
$http({
method: 'POST',
url: 'json/projects.json',
cache: true
}).then(function(data) {
languagesDeferred.resolve(data.data.languages);
});
this.getProjects = function(){
return projectsDeferred.promise;
};
this.getLanguages = function(){
return languagesDeferred.promise;
};
}]);
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projects = {};
$scope.languages = {};
var promise = projectService.getProjects();
promise.then(function(data) {
$scope.projects = data;
});
var promise = projectService.getLanguages();
promise.then(function(data) {
$scope.languages = data;
});
// This was a try, don't need to use this
$scope.getLanguage = function(name) {
array.forEach(function(element) {
if (element.name == name) {
$scope.push(element);
}
}, $scope.languages);
};
}]);
languages.json
{
"result":"SUCCESS",
"resultMessage":"",
"languages":[
{
"name":"CSharp",
"FullName":"C#",
"img":"img/languages/csharp.png"
},
{
"name":"Android",
"FullName":"Android",
"img":"img/languages/android.png"
},
{
"name":"VisualStudio",
"FullName":"Visual Studio",
"img":"img/languages/visualstudio.png"
}
]
}
projects.json
{
"result":"SUCCESS",
"resultMessage":"",
"projects":[
{
"name":"Test1",
"img":"img/projects/photo-1453060113865-968cea1ad53a.jpg",
"languages":["Android"]
},
{
"name":"Test2",
"img":"img/projects/photo-1454165205744-3b78555e5572.jpg",
"languages":["Android"]
},
{
"name":"Test3",
"img":"img/projects/photo-1457305237443-44c3d5a30b89.jpg",
"languages":["CSharp","VisualStudio"]
},
{
"name":"Test4",
"img":"img/projects/photo-1457612928689-a1ab27da0dad.jpg",
"languages":["CSharp","VisualStudio"]
}
]
}

Easy piece:
First don't use $q just use $http
app.service('projectService', ['$http', '$filter', function($http, $filter) {
function callLanguages(languages) {
return $http({
method: 'GET',
url: 'json/projects.json',
cache: true
}).then(function (response) {
return buildProjectWithLanguages(response.data.projects, languages);
});
}
function buildProjectWithLanguages (projects, languages) {
return projects.map(function (p) {
var langs = p.languages.map(function (l) {
var matchLangs = $filter('filter')(languages, { name: l });
if (matchLangs.length) {
return matchLangs[0];
} else {
return { FullName: l };
}
});
p.languages = langs;
return p;
});
}
this.getProjects = function(){
return $http({
method: 'GET',
url: 'json/languages.json',
cache: true
}).then(function(response) {
return callLanguages(response.data.languages);
});
};
}]);
then simplify your controller
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projects = [];
projectService.getProjects(function (projects) {
$scope.projects = projects;
});
}]);
and finally change your html to this:
<div class="container-fluid contentcontainer">
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<div class="languageoverlay">
<span ng-repeat="language in project.languages">
<img ng-src="{{language.img}}" ng-alt="{{language.FullName}}" />
<font ng-show="!$last">+</font>
</span>
</div>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
</div>

I really loved your awnser, but I made another approach with directives. I tested your awnser and it looks like a correct awnser.
This is what I did:
projects-directive.html
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<languages languagenames="project.languages"></languages>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
languages-directive.html
<div class="languageoverlay">
<span ng-repeat="language in languages">
<img ng-src="{{language.img}}" ng-alt="{{language.FullName}}" />
<font ng-show="!$last">+</font>
</span>
</div>
app.js
app.service('projectService', ['$http', '$filter', function($http, $filter) {
this.getLanguages = function() {
return $http({
method: 'GET',
url: 'json/languages.json',
cache: true
});
}
this.getProjects = function(){
return $http({
method: 'GET',
url: 'json/projects.json',
cache: true
})
};
}]);
app.directive('projects', ['projectService', function(projectService) {
return {
restrict: 'E',
templateUrl: "directives/projects-directive.html",
scope: {
limitto: "=?"
},
controller: function($scope)
{
projectService.getProjects().then(function(response) {
projects = response.data.projects;
if (angular.isDefined($scope.limitto))
{
$scope.projects = projects.slice(0, $scope.limitto);
} else {
$scope.projects = projects;
}
});
}
}
}]);
app.directive('languages', ['projectService', '$filter', function(projectService, $filter) {
return {
restrict: 'E',
templateUrl: "directives/languages-directive.html",
scope: {
languagenames: "="
},
controller: function($scope)
{
projectService.getLanguages().then(function(response) {
$scope.languages = $scope.languagenames.map(function (l) {
var matchLangs = $filter('filter')(response.data.languages, { name: l });
if (matchLangs.length) {
return matchLangs[0];
} else {
return { FullName: l };
}
});
});
}
}
}]);
app.controller('PortfolioController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projectlimit = 4;
}]);
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
}]);
How to call the directive:
<projects></projects>
and if you want to limit it, you can add parameter:
<projects limitto="projectlimit"></projects>

Related

call a controller inside another controller Angularjs

I have declared two HTML pages in my index: Home.html and jargon.html.
Each page has its own controller loaded in the application module.
angular.module('starter', ['ionic', 'ngRoute', 'starter.homeController', 'starter.jargonController'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
})
.state('jargon', {
url: 'jargon',
templateUrl: 'templates/jargon.html',
controller: 'jargonCtrl'
});
$urlRouterProvider.otherwise('/home');
});
My problem is that jargon.html has two other controllers:
<ion-view title="Jargon">
<ion-content>
<a class="item" href="#/jargon"></a>
<ion-pane ng-controller="CardsCtrl">
<div class="testimage">
<img ng-src="img/Logo.png" class="logo">
</div>
<swipe-cards on-card-swipe="onSwipe($event)">
<swipe-cards>
<swipe-card on-card-swipe="cardSwiped()" id="start-card">
</swipe-card>
<swipe-card ng-repeat="card in cards" on-destroy="cardDestroyed($index)" on-card-swipe="cardSwiped($index)">
<div ng-controller="CardCtrl">
<div class="image">
<img ng-src="{{card.image}}">
</div>
<div class="title">
{{card.Description}}
</div>
</div>
</swipe-card>
</swipe-cards>
</ion-pane>
</ion-content>
Controllers to manipulate the cards:
.controller('CardsCtrl', function($scope, $ionicSwipeCardDelegate) {
var cardTypes = [
{ image: 'img/cards/ASE card.png' },
{ image: 'img/cards/MCR-card.png' },
{ image: 'img/cards/R2A card.png' },
{ image: 'img/cards/RRH card.png' }];
$scope.cards = Array.prototype.slice.call(cardTypes, 0, 0);
//intialisation premiere carte
var newCard = cardTypes[0];
newCard.id = Math.random();
$scope.cards.push(angular.extend({}, newCard));
$scope.cardSwiped = function(index) {
$scope.addCard();
};
$scope.cardDestroyed = function(index) {
$scope.cards.splice(index, 1);
};
$scope.addCard = function() {
var newCard = cardTypes[Math.floor(Math.random() * cardTypes.length)];
newCard.id = Math.random();
$scope.cards.push(angular.extend({}, newCard));
}
})
.controller('CardCtrl', function($scope, $ionicSwipeCardDelegate) {
$scope.goAway = function() {
var card = $ionicSwipeCardDelegate.getSwipeableCard($scope);
card.swipe();
};
});
My question is: Where can I call both CardsCtrl and CardCtrl ? In the same jargonController.js file?
Here is a simple example:
<div ng-controller="HelloCtrl">
<p>{{fromService}}</p>
</div>
<br />
<div ng-controller="GoodbyeCtrl">
<p>{{fromService}}</p>
</div>
JavaScript:
//angular.js example for factory vs service
var app = angular.module('myApp', []);
app.service('testService', function(){
this.sayHello= function(text){
return "Service says \"Hello " + text + "\"";
};
this.sayGoodbye = function(text){
return "Service says \"Goodbye " + text + "\"";
};
});
function HelloCtrl($scope, testService)
{
$scope.fromService = testService.sayHello("World");
}
function GoodbyeCtrl($scope, testService)
{
$scope.fromService = testService.sayGoodbye("World");
}
http://jsfiddle.net/Ne5P8/2701/

Modify method to show success/failed Message. AngularJS

I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.
Heres the html code:
<form role="form">
<div class="panel-body">
<div class="panel-body">
<img src="/assets/doge.jpg" alt="Doge">
</div>
<div class="container">
<div class="input-group">
<span class="input-group-addon" id="tec-nombre">Nombre del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.nombre" aria-describedby="tec-nombre">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-legajo">Legajo del
Tecnico:</span><input type="number" class="form-control"
data-ng-model="tecnico.legajo" aria-describedby="tec-legajo">
<div role="alert">
<span class="error"
data-ng-show="myForm.legajoTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-email">Email del
Tecnico:</span><input type="email" class="form-control"
data-ng-model="tecnico.email" aria-describedby="tec-email">
<div role="alert">
<span class="error"
data-ng-show="myForm.emailTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-interno">Interno del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.interno" aria-describedby="tec-interno">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2"></label>
<div class="col-md-4">
Cancel
<a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar
{{tecnico.legajo}}</a>
<button data-ng-click="deleteCustomer(customer)"
data-ng-show="customer._id" class="btn btn-warning">Delete</button>
</div>
</div>
And heres the Angular Code:
angular.module('incidente', [ 'ngRoute' , 'ui.tree' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'partials/home.html'
}).when('/incidente/:codename', {
templateUrl : 'partials/incidente.html',
controller : 'IncidenteController'
}).when('/incidentes', {
templateUrl : 'partials/incidentes.html',
controller : 'IncidentesController'
}).when('/tecnicos', {
templateUrl : 'partials/tecnicos.html',
controller : 'TecnicosController'
}).when('/tecnico/:legajo', {
templateUrl : 'partials/tecnico.html',
controller : 'TecnicoController'
}).when('/sistema/:nombre', {
templateUrl : 'partials/sistema.html',
controller : 'SistemaController'
}).when('/sistemas', {
templateUrl : 'partials/sistemas.html',
controller : 'SistemasController'
}).when('/hardware/:codename', {
templateUrl : 'hardware.html',
controller : 'HardwareController'
}).when('/hardwares', {
templateUrl : 'partials/hardwares.html',
controller : 'HardwaresController'
}).when('/software/:codename', {
templateUrl : 'partials/software.html',
controller : 'SoftwareController'
}).when('/softwares', {
templateUrl : 'partials/softwares.html',
controller : 'SoftwaresController'
}).when('/readme', {
templateUrl : 'partials/readme.html',
controller : ''
}).when('/test', {
templateUrl : '/partials/tecnicos.html',
controller : 'TecnicosController'
}).otherwise({
redirectTo : '/'
});
} ])
.controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data;
})
})
.controller(
'navigation',
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
$scope.error = false;
} else {
$location.path("/login");
$scope.error = true;
}
});
};
})
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/" + code).then(
onIncidenteComplete, onError);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(urlbase + "set/incidente/" + incidente)
};
} ])
.controller(
'IncidentesController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onIncidenteComplete = function(response) {
try {
$scope.incidentes = angular
.fromJson(response.data);
console.log($scope.incidentes);
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/").then(
onIncidenteComplete, onError);
} ])
.controller(
'TecnicoController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var urlbase = "http://localhost:8080/";
var legajo = $routeParams.legajo;
var onTecnicoComplete = function(response) {
try {
$scope.tecnico = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/tecnico/" + legajo)
.then(onTecnicoComplete, onError);
$scope.saveTecnico = function(tecnico) {
return $http.post(urlbase + "set/tecnico/", tecnico)
};
This is the function that saves the tecnico and should show the error/success message.
} ])
.controller(
'TecnicosController',
[
'$scope',
'$http',
function($scope, $http) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
$http.get("http://localhost:8080/get/tecnico/")
.then(onTecnicoComplete, onError);
} ])
.controller(
'SistemasController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/get/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
$http.get(urlbase + "sistema/").then(
onSistemaComplete, onError);
} ]);
So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.
you could use
$scope.$on('$routeChangeStart', function(next, current) {
... you could trigger something here ...
});
and you should create a service that display something while changine route.
You have other events :
$routeChangeSuccess
$routeChangeError
$routeUpdate

How pass variables to directive from controller?

HTML:
<div ng-repeat="item in productArr">
{{ item.title }}
</div>
<div category-page-navigation current-page='currentPage' category-products-count='productsCount'></div>
JS:
.controller('categoryController', ['$scope', '$location', '$http', '$q', '$window', '$stateParams', function($scope, $location, $http, $q, $window, $stateParams) {
$scope.currentPage = 1;
$scope.productsCount = 0;
var GET = {
getProductData: function() {
var defer = $q.defer();
$http.post('services/loadProduct.php', {
'id' :1,
}).then(function(response) {
defer.resolve(response);
}, function(response) {
defer.resolve([]);
});
return defer.promise;
}
};
var getData = {
getProduct: function() {
var productData = GET.getProductData();
$q.all([productData]).then(
function(response) {
$scope.productArr = response[0].data.products;
$scope.productsCount = response[0].data.products.length;
});
}
};
getData.getProduct();
}])
.directive('categoryPageNavigation', function($compile, $parse) {
return {
scope: {
currentPage: '=currentPage',
categoryProductsCount: '=categoryProductsCount'
},
link: function (scope, element, attrs) {
debugger;
// Here scope.categoryProductsCount = undefined
// ...
$scope.$watch(scope.currentPage, function(value) {
// ...
});
}
};
});
I try to form new HTML for navigation to manipulate with HTML I get from ng-repeat.
In directive I need currentPage(from start =1) and total count of items from ng-repeat(length of array) witch I get from service. How I can pass variables to directive? First I need to get variables from service(ajax request or something else) then pass variables(some ather data) to directive.
If I understood correctly what you mean. Here is a code pen example on how to shared data between you controller and your directive.
A good read to understand the code below:https://docs.angularjs.org/guide/providers
http://codepen.io/chocobowings/full/Xmzxmo/
var app = angular.module('app', []);
//-------------------------------------------------------//
app.factory('Shared', function() {
return {
sharedValue: {
value: '',
}
};
});
//-------------------------------------------------------//
app.controller('ctrl', function($scope, Shared) {
$scope.model = Shared.sharedValue;
});
//-------------------------------------------------------//
app.directive('directive', ['Shared',
function(Shared) {
return {
restrict: 'E',
link: function(scope) {
scope.model = Shared.sharedValue;
},
template: '<div><input type="text" ng-model="model.value"/></div>'
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
Ctrl:
<div ng-controller="ctrl">
<input type="text" ng-model="model.value" />
<br/>
</div>
Directive:
<directive value="model.value"></directive>
</div>

UI-Router $stateParams With Master Detail Pattern

I need a Master Detais pattern for my web site. In index lots of thumbnails and every thumbnail link to their detailed page. I make a progress but does not get to work. Its load thumbnails on index oage but when I click to thumbnails its load blank page.
Index:
<body ui-view="viewA">
<div class="row" ui-view="viewB">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerikDetails({id:manga.id})" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url: "/",
views: {
"viewA": { templateUrl: "index.html",
controller: "indexCtrl",}
}})
$stateProvider
.state('icerik', {
url: "/icerik",
views: {
"viewB": { templateUrl: "icerik.html",
controller: "mmgCtrl",},
}})
$stateProvider
.state('icerikDetails', {
url: "/icerik/:id",
template: "<div>{{details }}</div>",
controller: "mmgCtrl",
resolve: {
getData : function(MY, $stateParams, $filter){
return MY.isimler.then(function(res){
return $filter('filter')(res.data, {id: $stateParams.id}, true)[0];
});}
}
})
$urlRouterProvider.otherwise("/");
})
factory and controllers:
.factory('MY', function($http){
var factory = {};
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen){
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
$scope.manga = getData.then(function(data){
$scope.details = data;
});})
I am not sure what you are trying to achieve, but at least I tried to convert your snippets into something working.
There is a working example
To get more understanding, do read these:
Nested States and Nested Views
Multiple Named Views
These are states, with a hiererchy. Index is super root, and details is super child:
$stateProvider
.state('index', {
url: "/",
views: {
"": {
templateUrl: "index.tpl.html",
controller: "indexCtrl",
}
}
})
.state('icerik', {
parent: "index",
url: "^/icerik",
views: {
"viewA": {
templateUrl: "icerik.html",
controller: "indexCtrl",
},
}
})
.state('icerik.icerikDetails', {
url: "/icerik/:id",
template: "<div>{{manga}}</div>",
controller: "mmgCtrl",
resolve: {
getData: function(MY, $stateParams, $filter) {
return MY.isimler.then(function(res) {
return $filter('filter')(res.data, {
id: $stateParams.id
}, true)[0];
});
}
}
})
$urlRouterProvider.otherwise("/");
These will be new controllers and factory:
.factory('MY', function($http) {
var factory = {};
//var url = '/uzak/remote.php?callback=JSON_CALLBACK';
var url = 'data.json';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen) {
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
//$scope.manga = getData.then(function(data){
// $scope.details = data;
// });
$scope.manga = getData;
})
And an example of templates "index.tpl.html":
<div >
<h2> this is index view</h2>
icerik
<div ui-view="viewA"></div>
</div>
and "icerik.html":
<div class="row" >
<div class="col s12 m6 l4" ng-repeat="manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerik.icerikDetails({id:manga.id})" class="thumbnail">
img src="/kapaklar/{{manga.kapak}}"
</a>
</div>
</div>
</div>
<hr>
<div ui-view=""></div>
</div>
Check it here

JSON request with Angular Displays an Empty Response

I believe Angular is loading the page before it receives all the information from JSONP. If I refresh the page a couple of times I do get the information to display; however, it is not constant. My code is almost the same as the code I am using on my projects page which does not have the same issue.
HTML:
<div class="container">
<div class="row push-top" ng-show="user">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1">
<div class="well well-sm">
<div class="row">
<div class="col-sm-3 col-md-2">
<img ng-src="[[ user.images.138 ]]" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-sm-7 col-md-8">
<h4 ng-bind="user.display_name"></h4>
<h5 ng-bind="user.occupation"></h5>
<i class="fa fa-map-marker"></i>
<cite title="[[ user.city ]], [[ user.country ]]">[[ user.city ]], [[ user.country ]]</cite>
<br>
<strong ng-bind="user.stats.followers"></strong> Followers, <strong ng-bind="user.stats.following"></strong> Following
<hr>
<p style="margin-top:10px;" ng-bind="user.sections['About Me']"></p>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScipt:
'use strict';
angular.module('angularApp')
.controller('AboutCtrl', function ($scope, $window, Behance) {
$scope.loading = true;
Behance.getUser('zachjanice').then(function (user) {
$scope.user = user;
$scope.loading = false;
}, function (error) {
console.log(error);
$scope.loading = false;
$scope.user = null;
});
$scope.gotoUrl = function (url) {
$window.location.href = url;
};
});
You can see the page in question at: http://zachjanice.com/index.html#/about. Thanks in Advance.
As requested here is the behance service:
'use strict';
angular.module('angularApp')
.factory('Behance', function ($http, $q, localStorageService, BEHANCE_CLIENT_ID) {
// Should be called to refresh data (for testing purposes)
// localStorageService.clearAll();
// Public API
return {
// Get a list of projects
getProjects: function (config) {
var pageNum = 1;
if (angular.isObject(config) && angular.isDefined(config.page)) {
pageNum = config.page;
}
var _projects = $q.defer(),
_storedProjects = localStorageService.get('Projects_Page_');
if (_storedProjects !== null) {
_projects.resolve(_storedProjects);
} else {
$http.jsonp('https://www.behance.net/v2/users/zachjanice/projects', {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK',
'page': pageNum
}
})
.then(function (response) {
if (response.data.http_code === 200 && response.data.projects.length > 0) {
// console.log('getting page', _page);
_projects.resolve(response.data.projects);
localStorageService.add('Projects_Page_' + pageNum, response.data.projects);
}
});
}
return _projects.promise;
},
// Get project with id
getProject: function (id) {
var _project = $q.defer();
$http.jsonp('https://www.behance.net/v2/projects/' + id, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_project.resolve(data.project);
});
return _project.promise;
},
// Get project with id
getUser: function (username) {
var _user = $q.defer();
$http.jsonp('https://www.behance.net/v2/users/' + username, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_user.resolve(data.user);
});
return _user.promise;
}
};
});
Anthony Chu supplied no support, so I found the answer myself. The issue was not the Behance Service, but the Projects Controller like I had originally stated.
I changed $scope.loading under the call for the service from false to true. Works every time.

Categories

Resources