AngularJS Routing problems with view - javascript

I'm trying to create a sigle-page app that contains shop list, in every shop card is the link to another view that contains table with products.
A shop looks like:
shop = {
id: 1,
name: "foo",
description: 'bar',
products: [item1, itemn];
};
app.js:
angular
.module('lightpointTestApp', [
'ngCookies',
'ngRoute',
'ui.sortable'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/products/:shopID', {
templateUrl: 'views/products.html',
controller: 'ProductsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Main.html view where are shop list:
<h3>Shop list</h3>
<div class="row shopsContainer" ui-sortable ng-model="shops">
<div class="col-lg-3 shopCard" ng-repeat="shop in shops">
<button class="btn close cardClose" ng-click="removeShop($index)">×</button>
<div class="cardNumber">{{ shops.indexOf(shop) + 1 }}</div>
<div class="cardHeader">{{ shop.name }}</div>
<div class="cardBody">
{{ shop.address }}<br />
{{ shop.hours }}<br />
View {{ shop.products.length }} products
</div>
</div>
</div>
<div class="row">
<input type="text" ng-model="newShop.name" placeholder="Shop name" class="col-lg-3" />
<input type="text" ng-model="newShop.address" placeholder="Shop address" class="col-lg-3" />
<input type="text" ng-model="newShop.hours" placeholder="Shop hours" class="col-lg-3" />
<button class="btn btn-primary col-lg-3" type="button" ng-disabled="!newShop.name || !newShop.address || !newShop.hours" ng-click="addShop()">Add Shop</button>
</div>
</span>
</div>
</div>
products.js - controller for products page
angular.module('lightpointTestApp')
.controller('ProductsCtrl', function ($scope, $routeParams, shops) {
$scope.shopList = shops;
$scope.shop = {};
$scope.getShop = function (id) {
for (var i = 0; i < $scope.shopList.length; i++) {
if ($scope.shopList[i].id === id) {
return $scope.shopList[i];
}
}
return null;
};
var shopID = $routeParams.shopID;
$scope.shop = $scope.getShop(shopID);
})
products.html where is the table with products
<h2>{{ shop.name }}</h2>
<table class="table table-hover">
<tr>
<th>Product Name</th>
<th>Product Description</th>
</tr>
<tr ng-repeat="product in shop.products">
<td> {{ product.name }} </td>
<td> {{ product.description }} </td>
</tr>
</table>
The problem is that products.html doesn't bind with products.js and show something like {{shop.name}} and an empty table.
P.S. I think that products.js isn't correct, but I tried everything to do it well.
Thanks.

You have a parameter shops in ProductsCtrl, but there is nothing that will pass a value for it, so it is going to be null. You set the value of $scope.shopList to it, and then try to iterate over a NULL array, so you get an exception.
You can store the values of shops in a service, and then pass them around your app via injection. You can initialize their values within main.js, or within the service itself, and then the values will be available if you inject them into ProductsCtrl, something like
angular.module('lightpointTestApp')
.controller('ProductsCtrl', ['$scope', '$routeParams', 'shopsService',
function ($scope, $routeParams, shopsService) {
$scope.shopList = shopService;
$scope.shop = {};
$scope.getShop = function (id) {
for (var i = 0; i < $scope.shopList.length; i++) {
if ($scope.shopList[i].id === id) {
return $scope.shopList[i];
}
}
return null;
};
var shopID = $routeParams.shopID;
$scope.shop = $scope.getShop(shopID);
}]);
shopsService could look something like
angular.module('lightpointTestApp')
.service('shopsService', function() {
return [
// add whatever fields you need here from code in main.js
{ name: 'shop1', address: 'addr1' },
{ name: 'shop2', address: 'addr2' }
];
});

Where are your shop objects coming from? You are passing in shop, in products.js but not referencing it in the code. You should also use $q to use promises for async data. Also use the filter() function rather than a for loop to find the shop by shopId.
Are you hitting an API with shops or storing a local json for now?
With angular, you should separate your data logic manipulation in a factory or service as such:
productService.js
angular.module('lightpointTestApp')
.factory('shopService',function($http, $q){
var shops = [];
return {
getShops: function () {
var deferred = $q.defer();
$http.get('<path to product.json or api>').success(function(data){
shops = data;
deferred.resolve(data);
})
return deferred.promise;
},
getShopById: function(shopID) {
var deferred = $q.defer();
deferred.resolve(shops.filter(function(chain){
return chain.id === shopID;
})[0]);
return deferred.promise;
}
}
});
product.js
angular.module('lightpointTestApp')
.controller('ProductsCtrl', function ($scope, $routeParams, $q,shopService) {
$scope.shopList = [];
$scope.shop = {};
var shopID = $routeParams.shopID;
shopService.getShops.then(function(shops){
$scope.shopList = data;
})
$scope.getShopById = function(shopID) {
shopService.getShopById(shopID).then(function(shop){
$scope.shop = shop;
});
}
});

Related

Sharing data from API between controllers in AngularJS

I have a parent controller with some children controllers, and I want them all to share the same data that I retrieve from an Api service.
Controllers:
var app = angular.module('mymodule',[]);
app.controller('main', ['$scope', 'Api', function($scope, Api) {
var getList1 = Api.getList1()
.then(function(resp) {
$scope.list1 = resp.data;
});
var getList2 = Api.getList2()
.then(function(resp) {
$scope.list2 = resp.data;
});
}]);
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = ?
$scope.list2 = ?
}]);
app.controller('child2', ['$scope', function($scope) {
$scope.list1 = ?
}]);
View:
<div ng-controller="main">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<ul>
<li ng-repeat="list in list2">
{{list.item}}
</li>
</ul>
</div>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
</div>
</div>
I tried to use this solution with Angular’s events mechanism ($on, $emit).
The problem was that I had to figure out which child controller is active and send the data when the promise has resolved. It ends with ugly spaghetti code...
Well, the best way is to use a service to have your API handling atomar placed inside your application. This fiddle shows you how you could achieve what you try to. By using AngularJS services you will be able to share the same data, objects and functions between controllers and let them interact with eachother. This is undepending on the amount of your controllers inside your application.
The following example is a full working API service with real HTTP-Requests and a real AngularJS service handling. It will help you by implement such logic inside your application. Please dont forget to check out the fiddle demo.
View
<div ng-controller="MyCtrl">
<h1>
MyCtrl
</h1>
<button ng-click="clearData()">
Clear data by using MyCtrl
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
<br /><br />
<div ng-controller="MyOtherCtrl">
<h1>
MyOtherController
</h1>
<button ng-click="clearData()">
Clear data by using MyOtherController
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);;
myApp.controller('MyCtrl', function ($scope, apiService) {
$scope.users = apiService.getResponseData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
});
myApp.controller('MyOtherCtrl', function ($scope, apiService) {
apiService.loadData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
})
myApp.service('apiService', function ($http) {
var responseData = null;
return {
loadData: function () {
return $http({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET'
}).then(function (response) {
responseData = response.data
});
},
getResponseData: function () {
return responseData
},
reset: function () {
responseData = null;
}
}
});
As your data is in the scope of the parent controller, you can access it in children controllers with $scope.$parent:
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = $scope.$parent.list1;
$scope.list2 = $scope.$parent.list2;
}]);
Write your children as directives, and then you can inject data on the scope.
yourModule.directive('child1', function() {
return {
scope: {list1:'=',
controller: function (scope) {
//not sure you even need a controller, but it might look like this
scope.doSomething = function() {
//access scope.list1 here
}
},
template: '<ul><li ng-repeat="list in list1">{{list.item}}<li><ul>'
}
}
Usage:
<child1 list1="list1"></child1>

Angular state resolve not injecting into controller

I'm trying to get ui-router's resolve to pass its value to the controller portalsForUserCtrl.
Here is the router:
(function () {
'use strict';
var myApp = angular.module("myApp", ["common.services", "ui.router", 'ngMessages']);
myApp.config(["$stateProvider", "$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("portalsForUser", {
url: "/userPortal/portalsForUser/:id",
templateUrl: "app/userPortal/portalsForUser.html",
controller: "portalsForUserCtrl as vm",
resolve: {
userPortalService: "userPortalService",
portalsForUser: function (userPortalService, $stateParams) {
var userId = $stateParams.id;
console.log(userId); //shows userId correctly
return userPortalService.getPortalsForUserPromise(userId)
.then(function (response) {
var userPortals = response.data;
console.log("userPortals", userPortals); //shows portals
return userPortals;
});
}
}
})
}]
);
Here is the entire controller:
(function () {
"use strict";
angular.module("myApp")
.controller("portalsForUserCtrl", portalsForUserCtrl);
portalsForUserCtrl.$inject = ['portalsForUser', 'userPortalService'];
function portalsForUserCtrl(portalsForUser, userPortalService) {
console.log("in portalsForUserCtrl");
var vm = this;
vm.portalsForUser = portalsForUser;
console.log(portalsForUser);
}
}());
In mainCtrl, which is the controller for index.html, I call:
$state.go("portalsForUser", ({ "id": userId }));
Here is the code for the view app/userPortal/portalsForUser.html:
<div class="container">
<table class="table table-condensed table-striped table-bordered">
<tbody>
<tr>
<th class="col-md-2"> </th>
<th class="col-md-4">
Portal Name
</th>
</tr>
<tr ng-repeat="userPortal in vm.portalsForUser">
<td>
{{userPortal.portal.portalName}}
</td>
<td class="">
<a class="btn btn-primary" ui-sref="goSomewhere({id: userPortal.portal.id})">
Go
</a>
</td>
</tr>
</tbody>
</table>
Here is the code for the userPortalService:
(function () {
"use strict";
angular.module("myApp")
.service('userPortalService', userPortalService);
userPortalService.$inject = ['userPortalResource', '$http', 'appSettings']
function userPortalService(userPortalResource, $http, appSettings) {
var getPortalsForUserPromise = function (id) {
return $http.get(appSettings.serverPath + '/api/UserPortal/GetPortalsForUser/' + id);
};
return {
getPortalsForUserPromise: getPortalsForUserPromise
};
}
}());
The url changes to the correct /userPortal/portalsForUser/:id but the portalsForUserCtrl function does not fire. It is only when I hit enter on the same url that portalsForUserCtrl is instantiated and the data appears in the view. What am I missing?
You have a syntax error in the $state.go statement.
Change this:
$state.go("portalsForUser", ({ "id": userId }));.
to this:
$state.go("portalsForUser", { "id": userId });
On the documentation (https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider) the specification of the method mentions the following:
The map object is:
key - {string}: name of dependency to be injected into controller
factory - {string|function}: If string then it is alias for service.
Otherwise if function, it is injected and return value it treated as
dependency. If result is a promise, it is resolved before its value is
injected into controller.
with the following as an example:
resolve: {
myResolve1:
function($http, $stateParams) {
return $http.get("/api/foos/"+stateParams.fooID);
}
}
So I suggest you change your code into one of these options to make it as simple a possible and, using chrome developer tool, place a breakpoint on the first line on the method:
resolve: {
portalsForUser: ['userPortalService', '$stateParams', function (userPortalService, $stateParams) {
var userId = $stateParams.id; //place your breakpoint here
return userPortalService.getPortalsForUserPromise(userId);
}]
}
Check what is going on with $stateParams; it is not impossible that, for some reason, at this moment, everything is not initialized yet because values don't come from the url, therefore, the id property is undefined. Try to inject "$state" and see if $state.params.id contains what you expect instead. (like mentioned in here: https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state).
Here is what it could look like:
resolve: {
portalsForUser: ['userPortalService', '$state', function (userPortalService, $state) {
var userId = $state.params.id; //place your breakpoint here
return userPortalService.getPortalsForUserPromise(userId);
}]
}
Hope that if it doesn't solve your problem, at least it will help you to find it.
EDIT:
It seems all the previous doesn't go to the right direction.
Here is my new direction:
I used your plunker to create a hosted site on my computer (using http-server: https://www.npmjs.com/package/http-server). My version that doesn't seem to be very different than yours works perfectly. Here is the full code:
app.js:
(function () {
'use strict';
var myApp = angular.module("myApp", ["ui.router"]);
myApp
.config(config)
.controller("portalsForUserCtrl", portalsForUserCtrl)
.service('userPortalService', userPortalService)
.controller("mainCtrl", mainCtrl)
mainCtrl.$inject = ["userPortalService", "$state"];
function mainCtrl(userPortalService, $state) {
var vm = this;
vm.clickMe = function () {
var userId = 1;
$state.go("portalsForUser", { "id": userId });
}
};
config.$inject=["$stateProvider"];
function config($stateProvider) {
$stateProvider
// PortalsForUser GET
.state("portalsForUser", {
url: "/userPortal/portalsForUser/:id",
templateUrl: "portalsForUser.html",
controller: "portalsForUserCtrl as vm",
resolve: {
portalsForUser: ['userPortalService', '$stateParams', function (userPortalService, $stateParams) {
return userPortalService.getPortalsForUserPromise($stateParams.id).then(function(response){return response.data;});
}]
}
})
}
userPortalService.$inject = ['$http', '$q', '$timeout']
function userPortalService($http, $q, $timeout) {
var getPortalsForUserPromise = function (id) {
var myId=id;
var deferred=$q.defer();
$timeout(function(){
deferred.resolve({data:[
{
id: 16,
portal: {
portalName: "Portal1-" + myId,
portalId: 1
}
},
{
id: 17,
portal: {
portalName: "Portal2-" + myId,
portalId: 2
}
}
]});
},5000);
return deferred.promise;
};
return {
getPortalsForUserPromise: getPortalsForUserPromise
};
};
portalsForUserCtrl.$inject = ['portalsForUser', 'userPortalService'];
function portalsForUserCtrl(portalsForUser, userPortalService) {
console.log("in portalsForUserCtrl");
var vm = this;
vm.portalsForUser = portalsForUser;
console.log(portalsForUser);
};
}());
index.html:
<html>
<head></head>
</html>
<body ng-app="myApp">
<!-- bower:js -->
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<!-- endbower -->
<!-- inject:js -->
<script src="app.js"></script>
<!-- endinject -->
<body ng-app="myApp" ng-controller="mainCtrl as vm">
<button type="submit" class="btn btn-default" ng-click="vm.clickMe()">
Click Me
</button>
<div ui-view></div>
</body>
</body>
portalsForUser.html:
<div class="container">
Portals For User
<table class="table table-condensed table-striped table-bordered">
<tbody>
<tr>
<th class="col-md-2"> </th>
<th class="col-md-4">
Portal Name
</th>
</tr>
<tr ng-repeat="userPortal in vm.portalsForUser">
<td>
{{userPortal.portal.portalName}}
</td>
<td class="">
<a class="btn btn-primary" ui-sref="goSomewhere({id: userPortal.portal.id})">
Go
</a>
</td>
</tr>
</tbody>
</table>
</div>
bower.json
{
"name": "test",
"description": "just a test",
"main": "index.js",
"authors": [
"me"
],
"license": "ISC",
"homepage": "index.html",
"private": true,
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"angular": "^1.5.8",
"angular-ui-router": "ui-router#^0.3.1"
}
}
I added the div ui-view in index.html like suggested by somebody else, but I believe this was already in your initial project.
I also tried to simulate the service like the real one would work (with a promise and with a property data).
Are you sure you have correct versions of ui-router and angular?
There might be an issue with dependency injection. Try this -
resolve: {
portalsForUser: ['userPortalService', '$stateParams', function (userPortalService, $stateParams) {
var userId = $stateParams.id;
return userPortalService.getPortalsForUserPromise(userId)
.then(function (response) {
var userPortals = response.data;
console.log("userPortals", userPortals);
return userPortals;
});
}]
}
Based in your code, I've seen that the your controller it's associated to the module clubSkedApp and your config it's associated to the myApp module.
Use the same module for both, or include the module of your controller like this.
var myApp = angular.module("myApp", ["clubSkedApp","common.services", "ui.router", 'ngMessages']);
Another approach is check why the state it's not loaded.
Ui-router isn't good to raise errors, the only way that i find to check the errors in a route's change is the following:
myApp.run(runFn);
runFn.$inject = ['$rootScope'];
function runFn($rootScope){
//Show the errores caused by the resolve function
$rootScope.$on('$stateChangeError', function (event, toState, toParams,
fromState, fromParams, error) {
event.preventDefault();
console.log(error);
});
}
I know the problem. The solution is very simple.
You need to add <div ui-view></div> into index.html to display your view in the later state like below code.
<body ng-app="myApp" ng-controller="mainCtrl as vm">
<button type="submit" class="btn btn-default" ng-click="vm.clickMe()">
Click Me
</button>
<div ui-view></div>
</body>
For more detail
Check the doc from UI-Router https://angular-ui.github.io/ui-router/
Check an example from my friend:
http://codepen.io/trungk18/pen/EgYyJd

$scope value is null in DOM

I am attempting to use ng-repeat with AngularJS but I am not getting the result of my scope in my DOM. Can anyone see the issue? I have been trying to troubleshoot this for hours and hours now and "players" is always null.
Here is my html:
<body ng-controller="CoachCtrl" >
<div class="mdl-tabs mdl-js-tabs mdl-js-ripple-effect">
<div class="mdl-tabs__tab-bar">
Starks
Lannisters
Targaryens
</div>
<div class="mdl-tabs__panel is-active" id="coach" >
<p>Number of players {{ players.length }}</p>
<table class="table">
<tr>
<th>Firstname
</th>
<th>Lastname
</th>
<th>Tryout Date
</th>
</tr>
<tr ng-repeat="kid in players" >
<td>{{ kid.firstname }}
</td>
<td>{{ kid.lastname }}
</td>
<td>{{ kid.tryout_date }}
</td>
</tr>
</table>
</div>
</div>
and here is my js:
'use strict';
angular.module('myApp.coach', ['ngRoute', 'firebase'])
// Declared route
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/coach', {
templateUrl: 'coach/coach.html',
controller: 'CoachCtrl'
});
}])
// Home controller
.controller("CoachCtrl", ["$scope", "$firebaseAuth", "$location",
function($scope, $firebaseAuth, $location) {
var ref = new Firebase("https://intense-heat-2545.firebaseio.com");
var authData = ref.getAuth();
if(authData){
console.log("User is "+authData.uid+" and is logged in with "+authData.provider);
var league = new Firebase("https://intense-heat-2545.firebaseio.com/users/"+authData.uid+"/league");
league.on("value", function(snapshot){
console.log("League ID = "+snapshot.val());
var leagueVal = snapshot.val();
var playerlist = new Firebase("https://blahblah.firebaseio.com/"+leagueVal+"/players");
$scope.players = [];
$scope.players.push({firstname:'John', lastname:'B', tryout_date:'2015-11-30'});
$scope.players.push({firstname: 'Marty', lastname: 'B', tryout_date: '2015-12-01'});
playerlist.on("child_added", function(snapshot){
//console.log("players ="+snapshot.val());
var player = snapshot.val();
console.log("Firstname ="+player.firstname);
var first = player.firstname;
var last = player.lastname;
var tyd = player.tryout_date;
console.log('player data ='+first+last+tyd);
$scope.players.push({ firstname: first, lastname: last, tryout_date: tyd });
var len = $scope.players.length;
for (var i = 0; i < len; i+=1){
if (1 === len){
console.log("player name = "+$scope.players[i].firstname);
}
}
console.log("players len ="+$scope.players.length);
}, function(error){
console.log("Error getting player info: "+error.code);
});
console.log("players ="+$scope.players[1].firstname+" len= "+$scope.players.length);
}, function(error){
console.log("Erro ="+error.code);
});
} else {
console.log("User is not logged in.");
$location.path('/signin');
}
}
]);
Three things.
The with the regular Firebase SDK Angular doesn't know when to run $digest.
Use $firebaseArray() rather than manipulating your own.
Use resolve() in the router to inject the user with $firebaseAuth().$waitForAuth().
-
var rootRef = new Firebase("https://<my-firebase-app>.firebaseio.com");
var leagueRef = rootRef.child("users").child(authData.uid).child("league");
// read it one time
leagueRef.once('value', function(snap) {
var leagueVal = snapshot.val();
var playerList = rootRef.child(leagueVal).child("players");
// $firebaseArray() will synchronize child events into an array
// Each update will know how to update $digest as well, which
// will keep the view updated.
$scope.players = $firebaseArray(playerList);
});
Your controller code would be greatly simplified if you use resolve in the router.
.constant('FBURL', '<my-firebase-app>')
.service('RootRef', ['FBURL', Firebase)
.factory('Auth', function($firebaseAuth, RootRef) {
return $firebaseAuth(RootRef);
})
.factory('UserLeague', function(RootRef) {
return function(uid) {
var leagueRef = RootRef.child("user").child(uid).child("league");
var deferred = $q.defer();
leagueRef.once(function(snap) {
deferred.resolve(snap.val());
});
return deferred.promise;
}
})
.config(function($routeProvider) {
$routeProvider.when('/coach', {
templateUrl: 'coach/coach.html',
controller: 'CoachCtrl',
resolve: {
leagueVal: function(UserLeague, Auth) {
var authData = Auth.$getUser();
return UserLeague(authData.uid);
},
authData: function(Auth) {
return Auth.$waitForAuth();
}
}
});
})
.controller("CoachCtrl", function($scope, leagueVal, authData, RootRef) {
// no need to check for a user because authData is injected
// use the resolved leagueVal to create a ref
var playerList = RootRef.child(leagueVal).child("players");
// synchronize the players to an array
$scope.players = $firebaseArray(playerList);
});

Angularjs : Print object from control to view with ionic

I try to build new APP with ionic framework and Angularjs.
Now my problem is i cannot show the result from controller to view. I try open console.log(allposts); in my browser ans we show the result good.
But in view its not show any thing
allpost.html
<dive class="item itemfull" ng-repeat="post in allpost">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news"><div class="title" ng-bind-html="post.content"></div></div>
</div>
</div>
</div>
And the controller
myApp.controller('allpost', function($scope , $http , $stateParams , Allposts) {
var id = $stateParams.id;
$scope.post = Allposts.GetAllposts(id);
});
myApp.factory('Allposts',['$http', '$q',function($http,$q){
var allposts = [];
var pages = null;
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
items = response.data.posts;
allposts = items;
console.log(allposts);
return items;
$ionicLoading.hide();
});
}
}
}]);
Where is error ?
try to change the code like this in controller and factory in js files
.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
})
.factory('Allposts', ['$http', '$q', function ($http, $q) {
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id=" +
id + "&status=publish");
}
}
}]);
the html file
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
It works for my test

AngularJS with UI-Route and Master Detail

I'm trying to get JSON data from my server and display them into my website. I am using Ui-router extension. What I am looking for here is a master-detail setup.
Index.html
<input ng-model="manga.name" ng-change="searchManga()" id="search" type="search" placeholder="Manga İsmi Girin..." required>
<div class="row" ui-view="viewA">
<div class="col s8 offset-s1" ng-controller = "nbgCtrl">
<div class="row">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="ui-sref="#/manga/{{manga.id}}"" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
</div>
<div class="col s7">
<p>{{manga.ad}}</p>
<a href="" class="waves-effect waves-light btn">
</a>
I have above a main page and repeating some thumbnails. Every thumbnail links to its detailed information page. And when clicking a thumbnail it has to carry its own data and load it here. Here's what I've got so far:
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('list', {
url: "/",
controller: "ListCtrl",
templateUrl: "index.html",
}
)
$stateProvider
.state('icerik', {
url: "/icerik/:{{mangaid}}",
controller: "mmgCtrl",
views: {
"viewA": { templateUrl: "icerik.html" },
}
}
)
})
.factory('Mangas', function($http){
var factory = {};
function getData(manganame, callbak) {
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
$http.get(url).success(function(data){
factory = data.results;
callback(data.results);
})
}
return {
list: getData,
find: function(name, callback) {
console.log(name);
var manga = cachedData.filter(function(entry) {
return entry.id == name;
})[0];
callback(manga);
}
};
})
.controller('ListCtrl', function($scope, $http, Mangas) {
$scope.manga = {
name: '' }
$scope.searchManga = function() {
Mangas.list($scope.manga.name, function(mangas) {
$scope.mangas = mangas;
});
}
})
.controller('mmgCtrl', function($scope, $http, $stateParams, Mangas) {
Mangas.find($stateParams.mangaid, function(manga) {
$scope.manga = manga;
});
})
I just doubt that the getData is not a promise in resolve closure you hava returned MY.isimler.then so in mmgCtrl controller first console getData to make sure it's a promise or data

Categories

Resources