AlBaraa Sh
AlBaraa Sh

Reputation: 2242

Using non-angular external js functions inside angularjs controller

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?

Upvotes: 0

Views: 2099

Answers (1)

Jochen van Wylick
Jochen van Wylick

Reputation: 5401

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();

Upvotes: 1

Related Questions