AngularJs is empty list - javascript

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

Related

Inject factory in controller use strict and named , IIEF functions

i'm using JHispter and i saw that uses these AngularJS rules: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
Using IIFE,Getters,Use Strict, Named Functions,ControllerAs,etc i would like to create a simple page that parse a JSON and show a movie list (title, director,duration) and the one that lasts much longer.
I've searched and tried all day but nothing works. The factory can't be used in the controller tough i inject it using $inject.
That's my index.html
<html>
<head>
<title>Hello Angular</title>
<link href="stile.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="">
</head>
<body ng-app="myApp">
<h1>Hello Angular</h1>
<div ng-controller="myController as sc">
<h1>angular JSON test</h1>
<!-- <p>Print movie list</p>
<ul >
<li ng-repeat="film in sc.elencoFilm">
{{film.title}}, {{film.director}}, {{film.time}}
</li>
</ul>
<p >Trova il film più lungo: {{sc.maxTimeFilm().title}} </p> -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="JS/app.config.js"></script>
<script src="JS/app.state.js"></script>
<script src="JS/app.service.js"></script>
<script src="JS/app.controller.js"></script>
</body>
</html>
My app.config.js
(function() {
'use strict';
angular
.module("myApp", []) ;
})();
My app.state.js
(function() {
'use strict';
angular
.module('myApp')
.config(stateConfig);
stateConfig.$inject = ['$routeProvider'];
function stateConfig($routeProvider) {
$routeProvider.when('/', {
templateUrl:"index.html",
controller:"serverController"
});
}
})();
My app.controller.js
(function () {
'use strict';
angular
.module("myApp",[])
.controller("myController", myController);
//myController.$inject = ['$scope', '$http'];
myController.$inject = ['$scope', '$http','myFactory'];
function myController($scope, $http, myFactory) {
//function myController($scope, $http){//, myFactory) {
var vm = this;
var elencoFilm={};
myFactory.getMovies().then(function (response) {
vm.elencoFilm = response;
});
vm.maxTimeFilm = getMaxTimeFilm();
function getMaxTimeFilm() { //return the longest film
}
}
})();
My app.service.js
(function () {
'use strict';
angular.module('myApp',[])
.factory('myFactory', myFactory);
myFactory.$inject = ['$scope', '$http','myFactory'];
function myFactory($scope, $http) {
console.log("sono nella factory");
return {
getMovies: function ($http) {
return $http.get('https://api.myjson.com/bins/1bgtg3');
/* .then(function (response) {
return response.data.movies;
});*/
}
}
}
})();
it always return this error:
https://docs.angularjs.org/error/$injector/unpr?p0=myFactoryProvider%20%3C-%20myFactory%20%3C-%20myController
it can't recognize myFactory into myController function!
in app.controller.js this line
function myController($scope, $http, myFactory) {
this break out the error!
Thank you for the help!! :)
Do not add empty dependency array in for module myApp in controller and factory.
Use .module('myApp') in both controller and factory, similar to your config.
By defining your modules based on functionality the myFactory service should be under a encapsulated closure referencing the main app module, hence all your factories can go under this module (ex. factories.module.js) :
(function() {
'use strict'
angular.module('myApp.factories', []);
}();
Once that module is added to your app.config
(function() {
'use strict'
angular.module('myApp', [
'myApp.factories'])
})();
It separates the concerns of your modules based on functionality following the IIFE design principle. Now reference your new module to myFactory in your service file.
(function () {
'use strict'
angular.module('myApp.factories')
.factory('myFactory', myFactory)
...
I've solved it!
i simply removed $scope from factory and removed [] in the controller definition (.module("myApp") insted of .module("myApp",[]) ).
#23rharris your advice is a best practice?
I've used the factory in each function of the controller every time i needed the JSON file :
myController.$inject = ['$scope', 'myFactory'];
function myController($scope, myFactory) {
...
vm.elencoFilm = getMovies();
function getMovies() {
myFactory.getMovies().then(function (response) {
...
...
vm.maxTimeFilm =getMaxTimeFilm();
function getMaxTimeFilm() {
myFactory.getMovies().then(function (response) {
if (response.data.movies != undefined) {
...
Is this the correct pattern for REST?

Keep getting AngularJS module not available (ASP.NET 5)

Trying to get simple Angular DI working in an existing ASP.NET 5 (Core) project.
Been following this tutorial.
Versions:
AngularJS 1.4.6
ASP.NET 5 (vNext)
Visual Studio 2015
Windows 10
Checked all the basic gotchas with naming and so on. Unclear about how my dependent js-files "controllers.js" & "services.js" are suppose to be discovered by Angular?
If I explicitly include them - which by the tutorial shouldn't be required - I still get
[ng:areq] Argument 'customerController' is not a function, got
undefined
Index.html
<!DOCTYPE html>
<html ng-app="bonusapp">
<head>
<meta charset="utf-8" />
<link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="lib/bootswatch/yeti/bootstrap.min.css" rel="stylesheet" />
<link href="css/main.css" rel="stylesheet" />
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script src="lib/app.js"></script>
<!--<script>angular.bootstrap(document, ['app']);</script>-->
</head>
<body ng-cloak>
<div id="wrapper" ng-controller="customerController">
<div id="main" class="container-fluid">
<div class="row">
<div class="col-md-3">
<h2>Kunder</h2>
<ul>
<li ng-repeat="item in Models">
{{item.FirstName}} {{item.LastName}} <a>Redigera</a> <a>Radera</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/jquery-validation/dist/jquery.validate.js"></script>
<script type="text/javascript" src="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>
app.js
(function () {
'use strict';
// Define module "app"
angular.module('bonusapp', [
// Angular modules
'ngRoute',
'ngResource',
// Custom modules
'customerService'
// 3rd Party Modules
]);
})();
controllers.js
(function () {
'use strict';
// Assign controller to app
angular
.module('bonusapp')
.controller('customerController', [
customerController]);
// $inject() method call is required to enable the controller to work with minification.
customerController.$inject = [
'$scope',
'Customers'
];
// Construct controller
function customerController($scope, Customers) {
// Populate model from service
$scope.Models = Customers.get();
}
})();
services.js
(function() {
'use strict';
var customerService =
angular
.module('customerService', ['ngResource']);
customerService
.factory('Customers',
['$resource'],
function ($resource) {
return $resource('/api/customers', {}, {
// Service call to get Customers
get: {
method: 'GET',
params: {},
isArray: true
}
});
}
);
})();
As Win suggested, I needed to:
Fix the include order to put jQuery first
Include all my JS files
But I still had some issues. For reference, here are the fixed scripts:
controller.js
(function () {
'use strict';
// Construct controller
// Remarks: controller is now declared FIRST
var customerController = function ($scope, Customers) {
$scope.Title = "Title";
// Populate model from service
$scope.Models = Customers.get();
}
// $inject() method call is required to enable the controller to work with minification.
customerController.$inject = [
'$scope',
'Customers'
];
// Assign controller to app
angular
.module('bonusapp')
.controller('customerController',
customerController);
})();
services.js
(function() {
'use strict';
var customerService =
angular
.module('customerService',
['ngResource']);
customerService
.factory('Customers',
['$resource',
function ($resource) {
return $resource('/api/customers', {}, {
// Service call to get Customers
// Remarks: 'get' in single quotes
'get': {
method: 'GET',
params: {},
isArray: true
}
});
}
]);
})();
You need to include controller.js and services.js files.
In addition, you need to move jquery before angular.js.
<script type="text/javascript" src="lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script src="lib/app.js"></script>
<script src="lib/controllers.js"></script>
<script src="lib/services.js"></script>
FYI: You might also want to look into bundling and magnification, before you publish.

Not able to select JSON index when using ngResource in factory

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

HTML page doesn't see AngularJS module

I am entirely new to AngularJS. The task is however simple: to parse XML file from the url and make a table out of it.
Yet somehow angular doesn't load. I searched similar questions, but neither worked. My index.html:
<!doctype html>
<html ng-app="myApp">
<head>
<title>jj</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular.intellisense.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/myscript.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">Text.</p>
</div>
<div ng-controller="AppController">
<h3>for example 2+3= {{3+2}}</h3>
</div>
</div>
</body>
</html>
I should get 5 instead of 2+3 if angular is loaded?
myscript.js currently looks like:
angular.module('myApp.service', []).
myApp.factory('DataSource', ['$http', function ($http) {
return {
get: function(file,callback,transform){
$http.get(
file,
{transformResponse:transform}
).
success(function(data, status) {
console.log("Request succeeded");
callback(data);
}).
error(function(data, status) {
console.log("Request failed " + status);
});
}
}
}]);
angular.module('myApp', ['myApp.service']);
var AppController = function ($scope, DataSource) {
var SOURCE_FILE = "guitars.xml";
xmlTransform = function (data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.customers.customer;
};
setData = function (data) {
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE, setData, xmlTransform);
};
Can you give me some advice?
It has to do with your syntax. I believe you have 2 errors. In your myscript.js you are declaring 2 modules. In your first module you are incorrectly declaring a factory. Use .factory not myApp.factory
angular.module('myApp.service', [])
.factory('DataSource', ['$http', function ($http) {
return {
// do something
}
}]);
In your second module you declare a function called AppController instead of calling the .controller angular method. Do this instead:
angular.module('myApp', ['myApp.service'])
.controller('AppController', ['$scope', 'DataSource', function ($scope, DataSource) {
// controller code
}]);
You can accomplish your program in a sole module by using a construct similar to what follows:
var app = angular.module('myApp', []);
app.controller('AppController', function($scope, DataSource) {
// code
});
app.factory('DataSource', ['$http', function($http) {
// code
}]);
Basically, create a variable for your app module, then call controller and factory, and pass your factory into your controller.

Configure and access AngularJS $scope by a third party application

I'm developing an AngularJS application and I would like to integrate some functions to let an other web-application interact with the application. My application should run and triggered on the same website. Iframes are not used.
The application has several tabs, and I would like to set a tab active by specifying it's id.
This has been done in an AngularJS controller, through this method:
$scope.setActiveTab = function(tabId) {
ribbon.setActiveTab(tabId);
$scope.$apply();
}
In my application, I have a ng-click attribute and this function is being called in it. But now, I do want a other application to set the active tab by calling some JavaScript function.
Therefore, I've written the following function:
$.fn.OfficeUI.EnableTab = function(element) {
angular.element($('#OfficeUI')).scope().setActiveTab('tabSendReceive');
}
However, this doesn't work, but when I past this method:
angular.element($('#OfficeUI')).scope().setActiveTab('tabSendReceive');
in the developer console of FireBug or Google Chrome, then it's working.
Any idea on what's wrong and how I should solve this?
Kind regards
As I understand you right. You need a application which allows developers (as you said Users :) to interact and configure your application by using HTML/JavaScript. Checkout this plunker demo.
A good approach is to do this with configuration files, global object, or events bindings. The following example shows you, how to let a user configure an a global config object in JavaScript & allows developers to interact with your application. For example by using $scopes.
Controller with global configuration object:
/**
* Active state holder
* #type {null|integer}
*/
var myConfig = {
menus : {
mainbar: {
active: true
},
subbar: {
active: false
},
othersubbar: {
active: false
}
}
};
var OfficeUIRibbon = angular.module('OfficeUIRibbon', [])
OfficeUIRibbon.factory('OfficeUIRibbonFactory', [function() {
return {
setActiveTabId: function (tabId) {
activeTabId = tabId;
}
}
}]);
OfficeUIRibbon.controller('OfficeUIRibbon', ['$scope', '$http', '$animate', function($scope, $http, $animate) {
//as scope set
$scope.isVisible = function (name){
if (myConfig.menus[name].active) {
return 'active';
}
}
$scope.activateMenu = function (name) {
console.log(name);
if (!myConfig.menus[name].active) {
myConfig.menus[name].active = true;
}
}
$scope.deactivateMenu = function (name) {
if (myConfig.menus[name].active) {
myConfig.menus[name].active = false;
}
}
$scope.listing = {
mainbar: {
id: 1,
label: 'mainbar'
},
subbar: {
id: 2,
label: 'subbar'
},
othersubbar: {
id: 3,
label: 'othersubbar'
}
}
}]);
HTML-Template:
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.angularjs.org/1.3.10/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="OfficeUIRibbon">
<ul>
<li ng-repeat="(key,list) in listing" ng-class="isVisible(key)">
{{ list.label }}
</li>
</ul>
<button ng-click="activateMenu('mainbar');">Activate Mainmenu</button>
<button ng-click="deactivateMenu('mainbar');">Deactivate Mainmenu</button>
</body>
</html>
User configuration, should be set before angular was loaded. For example, disable mainbar on default:
myConfig.menus.mainbar.active = false;
Please see demo below that should helps you.
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
$scope.test = function(msg) {
$scope.$apply(function() {
$scope.msg = msg
})
}
});
$(function() {
angular.element(document.querySelector('#contoller')).scope().test("Message for Angular from jQuery");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div id="contoller" ng-controller="firstCtrl">
{{msg}}
</div>
</body>
try:-
$scope.apply(function(){
angular.element($('#OfficeUI')).scope().setActiveTab('tabSendReceive');
})
You are in jquery scope you must have to use $scope.apply to reflect it to angular.

Categories

Resources