ngResource in factory works fine but unfortunately the result able to select JSON index. At the same time it is possible to bind the same $scope.resultItems variable
Console log appear like this 👇
Not working from ngResource http://codepen.io/anon/pen/dMbRXx
Working fine from variable http://codepen.io/anon/pen/ONLgNX
var app = angular.module('app', ['ngResource']);
app.controller('myCtrl', function($scope, categoryFilter) {
$scope.resultItems = categoryFilter.query();
$scope.resultIndex = $scope.resultItems[0];
$scope.resultIndexItem = $scope.resultItems[0].status;
});
app.factory('categoryFilter', function($resource) {
return $resource("https://maps.googleapis.com/maps/api/geocode/json?address=NY", {}, {
query: {
method: "GET"
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.5.0/angular-resource.min.js"></script>
<div class="container" ng-app="app" ng-controller="myCtrl">
<div class="col-xs-12">
<h3>ngResource result</h3>
<pre>{{resultItems | json }}</pre>
<hr />
<pre>{{resultIndex | json }}</pre>
<hr />
<pre>{{resultIndexItem | json}}</pre>
</div>
</div>
Each resource in fact is a ajax request that means it is asynchronous, So you have to use callbacks to query function. Then your code looks like this
var app = angular.module('app', ['ngResource']);
app.controller('myCtrl', function($scope, categoryFilter) {
categoryFilter.query(function(results){
$scope.resultItems = results;
$scope.resultItems.results[0];
$scope.resultIndexItem = $scope.resultItems.status;
});
});
app.factory('categoryFilter', function($resource) {
return $resource("https://maps.googleapis.com/maps/api/geocode/json?address=NY", {}, {
query: {
method: "GET"
}
});
});
link
Update
Sorry If I miss read you question, All items in json within {} will be an object can be accessed using ., For example in json results and status is object and items represented in [] is an array and they can be accessed using index.
From json
Related
I make simple program with .net Core and AngularJs + webApi
My Api code as below
There is no Js error after running the problem is factory return nothing.
when I set break point on $location.qwets = index.query(); my "qwets" is empty the length of "qwets" is 0.
The get method is working each time page refresh but result is nothing.
I changed the code now I have results in 'qwets' but index is still empty
Thank you
// GET: api/values
[HttpGet]
public IEnumerable<ApplicationUser> Get()
{
return new List<ApplicationUser> {
new ApplicationUser {Id="test", Email="test1#test.com" },
new ApplicationUser {Id="tst2",Email="test2#test.com" }
};
}
app.js File is
(function () {
'use strict';
angular.module('saniehhaApp', [
// Angular modules
//'ngRoute'
// Custom modules
"indexService"
// 3rd Party Modules
]);
})();
(function () {
'use strict';
angular
.module('saniehhaApp')
.controller('indexController', indexController);
indexController.$inject = ['$location', 'index'];
function indexController($location, index) {
index.query()
.$promise.then(function (result) {
$scope.qwets = result;
}
})();
(function () {
'use strict';
var indexService = angular.module('indexService', ['ngResource']);
indexService.factory('index', ['$resource',
function ($resource) {
return $resource('/api/index/', {}, {
query:
{
method: 'GET',
params: {},
isArray: true
}
});
}]);
})();
and my index.html file
<!DOCTYPE html>
<html ng-app="saniehhaApp">
<head>
<meta charset="utf-8" />
<title>SampleTest</title>
<script src="vendor/angular.min.js"></script>
<script src="vendor/angular-resource.min.js"></script>
<script src="vendor/angular-route.min.js"></script>
<script src="scripts/app.js"></script>
</head>
<body ng-cloak>
<div ng-controller="indexController"></div>
<h2>list of users</h2>
<ul>
<li ng-repeat="qwet in qwets">
<p> "{{qwet.Id}}" - {{qwet.Email}}</p>
</li>
</ul>
</body>
</html>
You are using $location and not $scope in the controller to assign properties needed in the view. The view doesn't see things in $location
Change to
function indexController($scope, index) {
/* jshint validthis:true */
$scope.qwets = index.query();
}
As mentioned in comments above, $resource will initially return an empty array (or object) that will subsequently be populated when the actual request completes and internal watchers will then update view when it arrives
Also bad end "div" in HTML ng-repeat not in div controller
I'm fairly new to Angular, and I'm trying to figure out why scope variables isn't updating after they've been set.
I'm calling a Node API returing json objects containing my data. Everything seems to work fine except setting $scope.profile to the data returned from the API.
Setup:
app.js
(function() {
var app = angular.module("gamedin", []);
app.controller('profileController', function($scope, $http, $timeout) {
$scope.profile = {};
$scope.getProfile = function() {
var vanityUrl = $scope.text.substr($scope.text.lastIndexOf('/') + 1);
$http.get('/steamid/' + vanityUrl)
.then(function(data) {
$http.get('/profile/' + data.data.response.steamid)
.then(function(data) {
console.log(data.data.response.players[0]); // Correct data
$scope.profile = data.data.response.players[0]; // View isn't updated
})
})
// Reset the input text
$scope.text = "";
}
});
...
app.directive('giHeader', function() {
return {
restrict: 'E',
templateUrl: 'components/header/template.html'
};
})
app.directive('giProfile', function() {
return {
restrict: 'E',
templateUrl: 'components/profile/template.html'
}
})
})();
components/header/template.html
<header>
<div class="header-content" ng-controller="profileController">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="header-content-inner">
<input ng-model="text" ng-keyup="$event.keyCode == 13 && getProfile()" class="form-control" type="text" placeholder="Enter Steam URL">
</div>
<p>e.g., http://steamcommunity.com/id/verydankprofilelink</p>
</div>
<div class="col-md-3"></div>
</div>
</header>
components/profile/template.html
<div class="container">
<div ng-controller="profileController">
<h3>
<strong>Username: {{ profile.personaname }}</strong>
</h3>
<p> SteamID: {{ profile.steamid }}</p>
</div>
</div>
index.html
<!doctype html>
<html ng-app="gamedin">
<head>
...
</head>
<body>
...
<gi-header></gi-header>
<gi-profile></gi-profile>
...
</body>
</html>
I've tried wrapping it in $scope.$apply, like this
$scope.$apply(function () {
$scope.profile = data.data.response.players[0];
});
... which resulted in Error: [$rootScope:inprog]
Then I tried
$timeout(function () {
$scope.profile = data.data.response.players[0];
}, 0);
and
$scope.$evalAsync(function() {
$scope.profile = data.data.response.players[0];
});
... and although no errors were thrown, the view still wasn't updated.
I realize that I'm probably not understanding some aspects of angular correctly, so please enlighten me!
The problem is that you have 2 instances of profileController, one in each directive template. They should both share the same instance, because what happens now is that one instance updates profile variable on its scope, and the other is not aware. I.e., the profileController instance of header template is executing the call, and you expect to see the change on the profile template.
You need a restructure. I suggest use the controller in the page that uses the directive, and share the profile object in both directives:
<gi-header profile="profile"></gi-header>
<gi-profile profile="profile"></gi-profile>
And in each directive:
return {
restrict: 'E',
scope: {
profile: '='
},
templateUrl: 'components/header/template.html'
};
And on a more general note - if you want to use a controller in a directive, you should probably use the directive's "controller" property.
Try using this method instead:
$http.get('/steamid/' + vanityUrl)
.then(function(data) {
return $http.get('/profile/' + data.data.response.steamid).then(function(data) {
return data;
});
})
.then(function(data) {
$scope.profile = data.data.response.players[0]; // View isn't updated
})
Where you use two resolves instead of one and then update the scope from the second resolve.
I am developing a CRUD interface for a Rest service. Currently, I could manage to get the list of teams in the system.
What I like to do is to show details for the when I click the show link. Currently clicking on the link calls a function (not yet implemented) that is supposed to load the details part into the ng-view. The function should pass a parameter to the ViewTeamController which will subsequently invoke the Rest service and give the result to a $scope variable.
I am not sure about how to call the ViewTeamController possibly using a URL encoded parameter from the showTeam() function. And I would also like to know how to read the URL-encoded parameter inside the ViewTeamController.
Thanks in advance.
<!doctype html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular-route.min.js"></script>
<script>
var teamApp = angular.module("teamApp", ['ngRoute']);
teamApp.controller('teamController', function($scope, $http) {
$http
.get('/teams')
.success(function(response) {
$scope.teams = response;
}
);
});
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addTeam', {
templateUrl: 'addTeam.htm',
controller: 'AddTeamController'
}).
when('/viewTeam', {
templateUrl: 'viewTeam.htm',
controller: 'ViewTeamController'
}).
otherwise({
redirectTo: '/addTeam'
});
}]);
mainApp.controller('AddTeamController', function($scope) {
});
mainApp.controller('ViewTeamController', function($scope) {
});
</script>
</head>
<body>
<div ng-app = "teamApp" ng-controller="teamController">
<a ng-click="newTeam()">new</a>
<div ng-repeat="team in teams" >
Name: {{team.name}}
<br />
Description: {{team.description}}
<br />
<a ng-click="showTeam(team.id)">show</a>
</div>
<div ng-view></div>
<script type = "text/ng-template" id = "addTeam.htm">
<h2> Add Team </h2>
To be implemented later.
</script>
<script type = "text/ng-template" id = "viewTeam.htm">
Name: {{team.name}}
Description: {{team.description}}
</script>
</div>
</body>
</html>
Your controller functions can get access to route parameters via the AngularJS $routeParams service like this:
mainApp.controller('ViewTeamController', function($scope, $routeParams) {
$scope.param = $routeParams.param; // will hold your encoded params
});
Considering you are passing the parameters as something like this in your URL,
/viewTeam/23535t4645645g4t4
Now your $scope.param will hold 23535t4645645g4t4
From this stackoverflow question, my understanding is that I should be using services to pass data between controllers.
However, as seen in my example JSFiddle, I am having trouble listening to changes to my service when it is modified across controllers.
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('App.data.status', function() {
$scope.status = App.data.status;
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('status', function() {
App.data.status = $scope.status;
});
})
.service('App', function () {
this.data = {};
this.data.status = 'Good';
});
In my example, I am trying to subscribe to App.data.status in Ctrl1, and I am trying to publish data from Ctrl1 to App. However, if you try to change the input box in the div associated with Ctrl2, the text does not change across the controller boundary across to Ctrl1.
http://jsfiddle.net/VP4d5/2/
Here's an updated fiddle. Basically if you're going to share the same data object between two controllers from a service you just need to use an object of some sort aside from a string or javascript primitive. In this case I'm just using a regular Object {} to share the data between the two controllers.
The JS
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.service('App', function () {
this.data = {status:'Good'};
});
The HTML
<div ng-controller="Ctrl1">
<div> Ctrl1 Status is: {{status}}
</div>
<div>
<input type="text" ng-model="localData1.status" />
</div>
<div ng-controller="Ctrl2">Ctrl2 Status is: {{status}}
<div>
<input type="text" ng-model="localData2.status" />
</div>
</div>
Nothing wrong with using a service here but if the only purpose is to have a shared object across the app then I think using .value makes a bit more sense. If this service will have functions for interacting with endpoints and the data be sure to use angular.copy to update the object properties instead of using = which will replace the service's local reference but won't be reflected in the controllers.
http://jsfiddle.net/VP4d5/3/
The modified JS using .value
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, sharedObject) {
$scope.localData1 = sharedObject;
})
.controller('Ctrl2', function ($scope, sharedObject) {
$scope.localData2 = sharedObject;
})
.value("sharedObject", {status:'Awesome'});
I agree with #shaunhusain, but I think that you would be better off using a factory instead of a service:
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.factory('App', function () {
var sharedObj = {
data : {
status: 'Good'
}
};
return sharedObj;
});
Here are some information that might help you understand the differences between a factory and a service: When creating service method what's the difference between module.service and module.factory
I'm trying to create a small note-taking application using AngularJS, but I stumbled at the very beginning. Here's my .js file:
var app = angular.module("app", ['ngResource']);
app.factory("note", ['$resource', function($resource){
return $resource("/api/notes/:id", {id:'#id'}, {
query: {method: "GET", isArray: true}});
}
]
);
app.controller("NotesController", function($scope, $note){
console.log("I am being constructed");
$scope.notes = $note.query();
});
And here's the html file:
<html>
<head>
<title>Jotted</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="js/controllers/controllers.js"></script>
<script src="http://code.angularjs.org/1.0.6/angular-resource.js"></script>
<link href='style/main.css' rel='stylesheet'>
</head>
<body ng-app="app" >
<div ng-controller="NotesController">
<div ng-repeat="note in notes">
{{note.title}}
</div>
</div>
</body>
</html>
I've tried adding
NotesController.$inject("$scope", "Note");
but it only gave ma an error saying that NotesController does not have a method named "$inject".
Nothing is displayed and the browser returns an error: "Error: Unknown provider: $noteProvider <- $note". Certainly I am missing something obvious, but I can't put my finger on it. Where does the problem lie?
Remove the $ Sign before your $note. The dollar Sign is only a convention of the Framework to identify internal Providers,... .
For example try:
var app = angular.module("app", ['ngResource']);
app.factory("note", ['$resource', function($resource){
return $resource("/api/notes/:id", {id:'#id'}, {
query: {method: "GET", isArray: true}});
}
]
);
app.controller("NotesController", function($scope, note){
console.log("I am being constructed");
$scope.notes = note.query();
});