Can someone please have a look at my js fiddle, I'm trying to get angular JS to display the list in the JSON file but I cannot get it working.
Very new to angular JS and trying to figure it out as I go
https://jsfiddle.net/2zumpvy9/
<body ng-app="DraftApp">
<div class="main" ng-controller="HomeController">
<div class="container">
<div class="each" ng-repeat="player in players">
{{ player.Player }}
</div>
</div>
</div>
</body>
var app = angular.module('DraftApp', []);
app.factory('players', ['$http', function($http) {
return $http.get('http://redraft.comxa.com/test.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
app.controller('HomeController', ['$scope', 'players', function($scope, players) {
players.success(function(data) {
$scope.players = data;
});
}]);
However, you can use the https://crossorigin.me/ service.
Then, you should request: «https://crossorigin.me/http://redraft.comxa.com/test.json». Finally, this can be easily used in your AngularJS code.
I've made a demo, using an AngularJS Service and Controller.
var app = angular.module("DraftApp", []);
app.factory("players", ["$http",
function($http) {
return $http.get("https://crossorigin.me/http://redraft.comxa.com/test.json")
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
]);
app.controller("HomeController", ["$scope", "players",
function($scope, players) {
players.success(function(data) {
$scope.players = data;
});
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="DraftApp">
<div class="main" ng-controller="HomeController">
<div class="container">
<div class="each" ng-repeat="player in players">
{{ player.Player }}
</div>
</div>
</div>
</body>
Related
I have two controllers
user.controller.js:
const fetchApi = () => {
console.log('fetching');
};
fetchApi();
I want to call this function in my dashboard.controller.js without writing this same hard code in dashboard controller again.
var app = angular.module('myapp', []);
var fetchApi = function($scope){
console.log("fetching");
};
fetchApi.$inject = ['$scope'];
app.controller('homeCtrl', fetchApi);
app.controller('dashboardCtrl', fetchApi);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="dashboardCtrl"></div>
<div ng-controller="homeCtrl"></div>
</div>
EDIT : inject service
var app = angular.module('myapp', []);
var fetchApi = function($scope, RestService){
console.log("fetching");
RestService.getUser();
};
fetchApi.$inject = ['$scope', 'RestService'];
app.controller('homeCtrl', fetchApi);
app.controller('dashboardCtrl', fetchApi);
app.service('RestService', ['$http',
function($http){
this.getUser = function() {
//$http api call
console.log("get user");
}
}
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="dashboardCtrl"></div>
<div ng-controller="homeCtrl"></div>
</div>
controller code:
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http) {
$http.get('data.json').then(function(data) {
$scope.artist = data;
});
});
html code:
<div class="main" ng-controller="myController">
<ul class="artistlist">
<li class="artist cf" ng-repeat="x in artist">
<img ng-src="images/{{x.shortname}}_tn.jpg" alt="Photo of {{x.name}}">
<div class="info">
<h2>{{x.name}}</h2>
<h3>{{x.reknown}}</h3>
</div>
</li>
</ul>
</div>
Try this: Your Controller
var myApp = angular.module('myApp', [])
myApp.controller("myController", ["$scope", "$http", function ($scope, $http) {
$http.get("data.json").then(
function (response) { $scope.artist = response.data },
function (error) { console.log(error) }
)
}])
Make sure you check the browser's console
The $http service has data property that is used to fetch the details.
data – {string|Object} – The response body transformed with the transform functions
Change your controller code like this
var myApp=angular.module('myApp',[]);
myApp.controller('myController', function($scope,$http){
$http.get('data.json').then( function(response){
$scope.artist = response.data;
});
});
And initialise your html with ng-app="myApp"
I have little problem with AngularJS, I wanted to make directive to display json imported from other website, directive working, but it doesnt show anything from angular binds(when i was using this code by just putting it hardway, everything was working).
HTML
<div ng-app="docsIsolateScopeDirective">
<div ng-controller="Controller">
<my-post info="post"></my-post>
</div>
</div>
ANGULAR
(function(angular) {
'use strict';
angular.module('docsIsolateScopeDirective', ['ngSanitize', 'ui.bootstrap'])
.controller('Controller', ['$scope','$http','$sce', function($scope, $http, $sce) {
$http.get(link+'json=get_recent_posts&callback=&count=1').then(function(response, date, contents){
$scope.contents = response.data.posts;
$sce.trustAsHtml(contents);
});
}])
.directive('myPost', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'single-post.html'
};
});
})(window.angular);
SINGLE-POST.HTML
<article>
<div class="news-container">
<span class="news-category">{{content.categories[0].title}}</span>
<h1 class="news-title">{{content.title}}</h1>
<span class="news-date">{{content.date}}</span>
<div class="news-image">
<img src="{{content.thumbnail_images.full.url}}" />
</div>
<!-- .news-image -->
<div class="news-entry">
<p ng-bind-html="content.content">{{content.content}}</p>
</div>
</div>
Any ideas? :)
You save your response as
$scope.contents = response.data.posts;
And you pass into directive variable post . Maybe you should pass contents ?
And also in your directive you have customerInfo not content.
its always better to use jsonp for calls to outer domains.
Can you try doing this?
$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
Whitelisting urls is also apt.
Pass $scope.contents to info.
$scope.contents = response.data.posts;
<div ng-app="docsIsolateScopeDirective">
<div ng-controller="Controller">
<my-post info="contents"></my-post>
</div>
</div>
You need to use customerInfo in the template single-post.html and also pass contents scope object to your directive
Additionally, Using trustAsHtml() method correctly.
$scope.contents = $sce.trustAsHtml(response.data.posts);
Here is a simplified example:
(function(angular) {
'use strict';
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope',
function($scope) {
$scope.contents = {
title: "test"
};
}
])
.directive('myPost', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
template: '<article>\
<h1 class="news-title">{{customerInfo.title}}</h1>\
</article>'
};
});
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="docsIsolateScopeDirective">
<div ng-controller="Controller">
<my-post info="contents"></my-post>
</div>
</div>
I am getting this error trying to set routes on 2 buttons. Please help me to find the reason for getting this error since everything looks in place and defined. The routes are working but I am not getting any data in the table.
I have: <html ng-app="myApp"> in the main htlm and the modules are not redefined anywhere. I checked other similar posts but I didn't find anything to address my problem.
Thank you.
The main html file snippet:
//main controller mainCtrl.js:
angular.module("myApp", [])
.controller('myAppCtrl',['getStockData','corsService','$scope', function(getStockData ,corsService, $scope) {
corsService.enableCors();
getStockData.getData().then(function(data){
$scope.products = data;
console.log("hello from ctrl",data);
});
}])
.controller('salesCtrl', function(getSalesData, $scope){
getSalesData.getData().then(function(data){
$scope.salesData = data;
console.log(data);
})
})
var app = angular.module("myApp");
//------------------------------------------------------------------------------
//route provider: routeProvider.js:
angular.module("myApp", ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider.when("/products", {
templateUrl: "views/productsView.html",
// controller:"myAppCtrl"
})
.when("/sales", {
templateUrl: "views/salesView.html",
})
.otherwise({
templateUrl: "views/productsView.html",
// controller: "myAppCtrl"
});
})
.controller("routeCtrl" ,function ($scope, $location){
$scope.setRoute=function(route){
$location.path(route);
}
});
//---------------------------------------------------------------------------------
//getting the data getStockData.js:
app.service('getStockData', function($http){
var dataUrl = "https://someAPI";
return {
getData: function() {
var successCallback = function (response){
//the response object
console.log("the response object:", response);
return response.data;
}
var errorCallback =function (reason){
//the reason of error message
console.log("error", reason.data);
return reason.data;
}
//Returns a Promise that will be resolved
// to a response object when the request succeeds or fails.
return $http.get(dataUrl)
.then(successCallback, errorCallback);
}
}
});
<body>
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">Beerbay</a>
</div>
<div ng-controller="routeCtrl" class="col-sm-1">
<a ng-click="setRoute('products')"
class="btn btn-block btn-primary btn-lg">Products</a>
<a ng-click="setRoute('sales')"
class="btn btn-block btn-primary btn-lg">Sales</a>
</div>
<ng-view />
</body>
<!--the partial view: productsView.html----------------------------------------->
<div class ="col-sm-11" ng-controller="myAppCtrl">
<!--displaying the data-->
<h4>Products</h4>
<table id="product_table" class="table">
<thead>
<tr>
<!-- table headers removed for brevity-->
</tr>
</thead>
<tbody>
<tr ng-repeat = "item in products|orderBy: 'name'">
<!-- table body removed for brevity-->
<!-- here I am displaying the products from the $scope-->
</tr>
</tbody>
</table>
</div>
<!--the other partial view: salesView--------------------------------------------->
<body>
<p>This is the sales view</p>
</body>
you are declaring myApp modules two times
1 ) angular.module("myApp", [])
2 ) angular.module("myApp", ["ngRoute"])
you are defining myAppcontroller on first module and after thatagain you declare same module
define mudule only once , after that you can access it like
var module = angular.module("myApp");
make these changes.
I am having a problem loading a set of JSON data with NG CLICK. Without the clickButton function the data loads fine. Is my JSON data structured properly? Here is my fiddle. Click [here] (http://jsfiddle.net/al321/08rjqv4k/3/ "mouse over")
$scope.items = [
{
"Name":"Sam",
"Address":"Street",
"Phone":"111",
"status":"Available"
},
{
"Name":"Tom",
"Address":"Road",
"Phone":"222",
"status":"Busy"
},]
--js
var app = angular.module('myApp', []);
app.controller('myController',
['$scope', '$http', function($scope, $http) {
$scope.clickButton = function() {
$http.get('data.json').success(function(data) {
$scope.items = data.items;
});
}
}]);
Plunker
JS
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
$scope.clickButton = function() {
$http.get('data.json').success(function(data) {
$scope.items = data;
});
}
}]);
Markup
<body ng-controller="myController">
<div ng-app="myApp">
<div ng-controller="myController">
<button ng-click='clickButton()'>Load Data</button>
<ul ng-repeat="item in items">
<li ng-repeat="(key, val) in item">{{key}}: {{val}}
</li>
</ul>
</div>
</div>
</body>
JSON
[
{
"Name":"Sam",
"Address":"Street",
"Phone":"111",
"status":"Available"
},
{
"Name":"Tom",
"Address":"Road",
"Phone":"222",
"status":"Busy"
}
]
Is this what you are trying to accomplish?
Just replace the contents of the clickButton() function with your ajax calls.
You forgot to put the () on ng-click="clickButton(). You need to actually call the function.
Plunker
To add the search functionality you mentioned in the comment, just add a filter to the first ng-repeat:
ng-repeat="item in items| filter: {Name: search}"
Plunker with search