I'm still new to angularJs.
I need to access Enumerable class from linqjs inside an angularjs controller.
My ngController looks similar to this:
var app1= angular.module("app1");
app1.controller("peopleController", ['$scope', 'Restangular',
function($scope, Restangular) {
$scope.people = Restangular.all('people').getList()
$scope.selectedItem = Enumerable.From(people).FirstOrDefault(); // ERROR
}]);
The error I'm getting is:
ReferenceError: Enumerable is not defined
any help?
I think it should be:
var app1 = angular.module("app1");
app1.controller("peopleController", ['$scope', 'Restangular', function ($scope, Restangular) {
$scope.people = Restangular.all('people').getList();
$scope.selectedItem = Enumerable.From(people).FirstOrDefault(); // ERROR
}]);
So without the 'peopleController' name of the function.
Edit
The problem is that Enumerable ( which is defined in linqjs ) is not available at the moment that it is called. Therefore the injector is looking for it and for the Enumerableprovider, but it doesn't exist nor is it injected.
You want to make sure you load the linqjs sources before your application is run. If Enumerable is defined in the global scope, you should be fine to use it from your controller. I created a JsFiddle that loads angular and linqjs from a CDN and shows you that it will 'just work' from your controller: http://jsfiddle.net/ngn3Lprx/2/
var app = angular.module('myapp', []);
app.controller('myctrl', ['$scope', function ($scope) {
// Example from: http://linqjs.codeplex.com/
var jsonArray = [
{ "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" },
{ "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" },
{ "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" },
{ "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }
]
// ["b_mskk:kabushiki kaisha", "c_bill:g", "d_linq:to objects"]
$scope.queryResult = Enumerable.From(jsonArray)
.Where(function (x) { return x.user.id < 200 })
.OrderBy(function (x) { return x.user.screen_name })
.Select(function (x) { return x.user.screen_name + ':' + x.text })
.ToArray();
}]);
With view:
<div ng-app="myapp">
<div ng-controller="myctrl">
<pre>
{{ queryResult | json }}
</pre>
</div>
</div>
Gives:
[
"b_mskk:kabushiki kaisha",
"c_bill:g",
"d_linq:to objects"
]
As expected.
p.s. Dont' forget the semi-colon after .getList();
Related
Background: I'm making a simple Ionic project about the NYC Subway. I am using the Ionic "tabs" template, and I have a tab that lists all of the routes with their symbols (1, 2, 3, A, C, E, etc.) and the user should be able to click on any of the routes listed there and be taken to a detail page (kind of like how they have a "Chats/Chat Detail" setup in the tabs template when you start a new ionic project).
The problem is I can't seem to get the Route Detail page to load information about the selected route. Expressions like {{route.name}} and {{route.desc}} come up blank.
routes.json file (sample, filed under www/js/routes.json):
{
"routes": [{
"id": "1",
"name": "1",
"desc": "7 Avenue Local",
"className": "c123"
},
{
"id": "2",
"name": "2",
"desc": "7 Avenue Express",
"className": "c123"
},
{
"id": "3",
"name": "3",
"desc": "7 Avenue Express",
"className": "c123"
},
...
app.js:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
// ...
.state("tab.routes", {
url: "/routes",
views: {
"tab-routes": {
templateUrl: "templates/tab-routes.html",
controller: "RoutesCtrl"
}
}
})
.state("tab.route-detail", {
url: "/routes/:id",
views: {
"tab-routes": {
templateUrl: "templates/route-detail.html",
controller: "RouteDetailCtrl"
}
}
});
controllers.js:
angular.module('starter.controllers', [])
// ...
/* This one works perfectly */
.controller('RoutesCtrl', function($scope, $http) {
$http.get("js/routes.json").then(function(response) {
$scope.routes = response.data.routes;
console.log($scope.routes);
});
})
/* This one does NOT work */
/* $stateParams.id returns the correct value, but $scope.route
does not store the Route returned from the service (null) */
.controller("RouteDetailCtrl", function($scope, $stateParams, Routes) {
$scope.route = Routes.getRoute($stateParams.id);
})
services.js:
angular.module('starter.services', [])
/* This is the problem */
.factory("Routes", function($http) {
return {
getRoute: function(id) {
return $http.get("js/routes.json").then(function(response) {
var routes = response.data.routes;
for(var i = 0; i < routes.length; i++) {
if(parseInt(id) === parseInt(routes[i].id)) {
return routes[i];
}
}
return null;
})
}
}
})
I think the problem has something to do with the way the JSON is coming back in services.js - is it the way my JSON is stored, or the way I'm "parsing" it on the receiving end? The "RoutesCtrl" works just fine, but I can't seem to get the route detail working no matter what variation of response I use in services.js - I have tried response, response.data, response.data.routes, nothing works.
route-detail.html: (as you can see, {{route.whatever}} refers to the $scope.route in controllers.js but it's not getting stored).
<ion-view view-title="{{route.name}}">
<ion-content class="padding">
<h2>{{route.name}}</h2>
<h2>{{route.desc}}</h2>
<p>This is the detail page.</p>
</ion-content>
</ion-view>
The problem is not with the routes object as the same code works fine in RoutesCtrl but with the way youare handling the response in RouteDetailCtrl. The response returned from Route service is not an primitive javascript values but a promise and you need to handle the promise correctly to get your response:
.controller("RouteDetailCtrl", function($scope, $stateParams, Routes) {
Routes.getRoute($stateParams.id)
.then(function (response) {
$scope.route = response;
});
})
I am creating a simple pattern library with an index page of HTML patterns, and individual pages for each pattern.
I am thinking that I should create a "pattern" directive that would include the template for the index page patterns. Like this:
<pattern></pattern>
which would show:
<section ng-repeat="pattern in patterns | orderBy:'title'" class="pattern-type" data-anchor="{{pattern.anchor}}" id="{{pattern.id}}">
<h3>{{pattern.title}} individuals/{{pattern.anchor}}</h3>
<div class="pattern-desc" ng-show="pattern.description">
<p>{{pattern.description}}</p>
</div>
<div class="pattern" ng-include="'individuals/' + {{pattern.anchor}}"></div>
<div class="pattern-status">
Date Posted: <span class="date"> {{pattern.updated | date:'yyyy-MM-dd'}}</span>
</div>
</section>
I would create a separate "individual" directive for the individual pattern display template. My app.js look like this:
app.directive('pattern', function() {
return {
restrict: 'E',
templateUrl: 'pattern.html',
controller: function() {
$http.get('assets/js/components.json')
.then(function(result) {
$scope.patterns = result.data;
});
},
controllerAs: 'patterns'
};
});
And my JSON looks like this:
[{
"id": "alerts",
"anchor": "alerts",
"title": "Alerts",
"description": "This is a desc",
"guidelines": "",
"updated": "2015-06-26"
},
{
"id": "buttons",
"anchor": "buttons",
"title": "Buttons",
"description": "",
"guidelines": "",
"updated": "2015-04-15"
}]
However nothing is showing up. What am I missing?
Your directive controller has missing $http & $scope dependency inside its function.
Code
controller: function($scope, $http) { //<-- added dependency here
$http.get('assets/js/components.json')
.then(function(result) {
$scope.patterns = result.data;
});
},
Working Plunkr
I am trying to learn how to unit test within angular. Unit testing my controllers to start with then my services.
I have started off with a basic test.
Controller code:
angular.module('app')
.controller('TestCtrl', function ($rootScope,$scope,fileLoader,ngProgress) {
$scope.test= [];
$scope.init = function(){
fileLoader.getFile("test")
.then(function(res){
//Success
console.log(res);
$scope.test= res;
}, function(err){
//Error
});
ngProgress.complete();
}
$scope.init();
$scope.title = "Test";
});
Test code:
describe('Controller: TestCtrl', function () {
// load the controller's module
beforeEach(module('app'));
var TestCtrl,
scope,test;
test = {};
test.getFile = function(name) {
return [
{
"id": 0,
"name": "Test",
"imgName": "Test.png"
},
{
"id": 1,
"name": "Test1",
"imgName": "Test1.png"
}];
};
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
TestCtrl= $controller('TestCtrl', {
$scope: scope,
fileLoader : test
});
}));
it('should have the correct title', function () {
expect(scope.title).toBe("Test");
});
});
And I can't understand why I am getting the following error:
TypeError: 'undefined' is not a function (evaluating
'fileLoader.getFile("test")
.then') undefined
Is there any way once this is resolved I can lay all my mocking out in a separate file e.g. my fileLoader mock and just inject it that way?
I don't understand how I am injecting it but yet it is undefined.
Thanks
And I can't understand why I am getting the following error:
you defined
fileLoader.getFile("test")
.then(function(res){
so getFile() should return a promise which could be resolved, but you return a simple array with two objects inside
test.getFile = function(name) {
return [
{
"id": 0,
"name": "Test",
"imgName": "Test.png"
},
{
"id": 1,
"name": "Test1",
"imgName": "Test1.png"
}]
refactor one side. Use defers or handle the array result.
Please can anyone explain why the following throws an "Argument 'MainCtrl' is not a function, got undefined" error which seems to be tied into the use of module dependency injection with directives(?!).
angular.module('app', [])
.controller('MainCtrl', [function() {
var self = this;
self.name = "will this work";
self.items = [
{
name: "name 1",
test: "test 1"
},
{
name: "name 2",
test: "test 2"
}
];
}]);
angular.module('app',[])
.directive('typeahead', [function() {
return {
templateUrl: 'type-ahead.html',
restrict: 'AEC',
scope: {
items: '=',
prompt: '#',
title: '#',
subtitle: '#',
model: '=',
onSelect: '&'
}, <...more code>
Yet it will work perfectly fine when I remove the
[ ]
module dependency braces from the directive to read
angular.module('app').directive('typeahead', ...)
It also works perfectly fine if I define the directive as a cascade following the controller definition i.e.
angular.module('app', [])
.controller('MainCtrl', [function() {
var self = this;
self.name = "will this work";
self.items = [
{
name: "name 1",
test: "test 1"
},
{
name: "name 2",
test: "test 2"
}
];
}])
.directive('typeahead', [function() {
return {
Thanks in advance!
You are running into Angular's Creation versus Retrieval Problem:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
The first time you run angular.module('app',[]), Angular will create a module called app. Next time, you only need to run angular.module('app'), Angular will try to load the existing module app.
Since you call angular.module('app',[]) once again, module app has been re-initialized. That's why MainCtrl is undefined now.
I'm an beginner in angularjs and don't have any idea about web services either. My requirement is something like this:
I have to get a JSON object from my url http://mylocalhostname.dev/users/list?city_id=12
I'm absolutely clueless...Please help me out by modifying my code.
Thanks in advance. Here's my JS code:
'use strict';
var services = angular.module('services', ['ngResource']);
services.factory('dataFactory', ['$resource','$http', '$log',
function ($resource, $http, $log) {
return {
getAllUsers: function(){
return $resource('http://mylocalhostname.dev/users/list',{city_id:12}
,{
locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter)
$log.info(data.UsersList[0]);
return data.UsersList[0].userName;
})}
}
);
}
}
}]);
when i test i get this message in my console :
GET http://mylocalhostname.dev/users/list?city_id=12 200 OK 164ms angular.js (ligne 7772)
(in color red)
(an empty string)
(I realize this is an ancient question, but still unanswered, and it appeared at the top of a search I just did, so hopefully this can close that particular loop)
Simple example of a controller retrieving data from a simple factory, where the factory is using $resource to access a locally-hosted file and returning contents of file back to the controller.
The factory:
'use strict';
angular.module('myApp')
.factory('myFactory', ['$resource', function($resource) {
return function(fileName){
return $resource(fileName, {});
};
}]);
The controller:
'use strict';
var fileToGet = 'some/path/to/file.json';
angular.module('myApp')
.controller('myController', function($scope, myFactory) {
var getDefs = new myFactory(fileToGet).get(function(data) {
$scope.wholeFile = data;
// $scope.wholeFile should contain the entire JSON-formatted object
$scope.someSection = data.section;
// $scope.someSection should contain the "varX" and "varY" items now
$scope.myStringX = JSON.stringify(data.section.varX);
// get the stringified value
});
});
The JSON-formatted file:
{
"someVar": "xyz",
"someArray": [
{
"element0A": "foo",
"element0B": "bar"
},
{
"element1A": "man",
"element1B": "chu"
}
],
"section": {
"varX": 0,
"varY": "yyyy"
}
}