Loading JSON Data via NG click (JS) - javascript

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

Related

Not getting json data from json-angularjs call to an external url with $http.get

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"

AngularJS json url not working

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>

Adding function dynamical to angular objects

How to add a function to a angular object dynamical to the onclick or click event?
Adding onclick={{item.function}} or ng-click={{item.function}} won't work
JS
angular
.module('app', [])
.controller('MainController', ['$scope', function($scope) {
$scope.test = function() {
alert(1);
};
$scope.items = {
'item1': {
name: 'Item1',
function: 'test()' // Not calling
}
};
}]);
Html
<html ng-app="app">
<body ng-controller="MainController">
<ul ng-repeat="item in items">
<li ng-bind="item.name" ng-click="item.function"></li>
</ul>
</body>
</html>
Not working demo
http://codepen.io/anon/pen/jqEKRP
In controller:
...
'item1': {
name: 'Item1',
f: $scope.test
}
...
In template:
<li ng-bind="item.name" ng-click="item.f()"></li>
http://codepen.io/bparnikel/pen/bpNjoE

Angularjs: Callback to parent controller

Please consider the following code: it has a directive myItem with isolate scope. Each item will display a button that will call delete() on the directive controller. I'd like this to trigger a refresh in the outer controller (AppController). But of course the refresh() function can not be found, because of the isolated scope.
<html>
<body ng-app="question">
<div ng-cloak ng-controller="AppController">
<my-item ng-repeat="item in list" data="list">
</my-item>
<input type="text" maxlength="50" ng-model="new_item" />
<button ng-click="add(new_item)">+</button>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
(function () {
var app;
app = angular.module('question', []);
app.controller('AppController', [
'$scope', '$http', function ($scope, $http) {
$scope.list = [];
function refresh(){
$http.get('/api/items').then(
function(response){
$scope.list = response.data;
}
);
}
$scope.add = function(item){
$http.post('/api/items', { item: item }).then(refresh);
};
refresh();
}
]);
app.directive('myItem', function() {
return {
scope: {
item: '=data',
},
// directive template with delete button
template: '{{ item }} <button ng-click="delete(item)">-</button>',
restrict: 'E',
// directive controller with delete function
controller: [ '$scope', '$http', function($scope, $http) {
$scope.delete = function (card) {
// This is where it goes wrong! refresh does not exist
$http.delete('/api/items' + card.id).then(refresh);
}
}]
};
});
})();
</script>
</body>
</html>
One thing I could do is add ng-change to the myItem directive, but that would involve requiring ngModelController which seems overkill.
Other things I can think of:
Add something like onchange: '#' to the scope attribute of the directive, then set onchange = refresh in the html. Call the onchange expression instead of refresh inside the delete function. But this feels like I'm re-implementing ng-change?
Add require: '^AppController' to the directive. Then I guess I could call refresh on the parent controller directly. That seems like it violates loose coupling.
Don't use isolate scope at all. That would mean we inherit from the parent scope and refresh is available. But then my directive implicitly assumes that the scope will hold an item. Which also violates loose coupling, but in an implicit way.
So my question is: which is the correct way to let the parent controller know it should refresh its contents?
IMO, the first way would be the best way. The directive receives a function callback from outside which is executed by the directive when necessary. Like this the two directives are loosely coupled. It's similar to ng-change which is an attribute that is used by ng-model directive.
Example: Directive
app.directive('myItem', function() {
return {
restrict: 'E',
scope: {
item: '=data',
myItemDeleteCallback: '&myItemDeleteCallback'
},
template: '{{ item }} <button ng-click="delete(item)">-</button>',
controller: [ '$scope', '$http', function($scope, $http) {
$scope.delete = function (card) {
// This is where it goes wrong! refresh does not exist
$http.delete('/api/items' + card.id).then(function () {
$scope.myItemDeleteCallback();
});
}
}]
};
});
Usage: Controller
app.controller('AppController', ['$scope', '$http', function ($scope, $http) {
$scope.list = [];
$scope.refresh = function (){
$http.get('/api/items').then(
function(response){
$scope.list = response.data;
}
);
};
$scope.add = function(item){
$http.post('/api/items', { item: item })
.then($scope.refresh);
};
refresh();
}]);
Usage: Template
<div ng-cloak ng-controller="AppController">
<my-item my-item-delete-callback="refresh()" ng-repeat="item in list" data="list">
</my-item>
<input type="text" maxlength="50" ng-model="new_item" />
<button ng-click="add(new_item)">+</button>
</div>

How to write HTML code inside of DIV after send POST request in AngularJs

I want to write HTML code inside of DIV after getting data from service but it doesn't work. These are my html and js codes. How can I fix?
Thanks.
index.html:
<html>
<head>
<title>AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-sanitize.js"></script>
<script src=script></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<div ng-bind-html="htmlcode">
</div>
</div>
</body>
</html>
script.js:
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
html = "<ul><li>Item-1<ul><li>SubItem-1</li></ul></li><li>Item-2</li></ul>";
$scope.htmlcode= html;
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
});
}]);
})(window.angular);
script1.js:
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
html = "<ul><li>Item-1<ul><li>SubItem-1</li></ul></li><li>Item-2</li></ul>";
$scope.htmlcode= html;
});
}]);
})(window.angular);
RESULT (script1.js):
Item 1
Item 2
SubItem-1 is not shown as a sub item of Item-1
RESULT (script.js):
Item 1
SubItem-1
Item 2
Do not manipulate html inside the controller use diectives or services for that. This should be done with an ng-repeat instead.
(function(angular) {
'use strict';
angular.module('myApp', ['ngSanitize'])
.controller('myController', ['$window', '$scope', '$http', function($window, $scope, $http) {
$scope.items = [];
var res = $http.post(service_url);
res.success(function(result, status, headers, config) {
$scope.items.concat(result.items);
});
}]);
})(window.angular);
// template
<body ng-app="myApp">
<div ng-controller="myController">
<ul class="items">
<li ng-repeat="item in items">
{{item.name}}
<ul class="sub-items">
<li ng-repeat="subitem in item.subItems">{{subitem.name}}</li>
</ul>
</li>
</ul>
</div>
</body>
// items.json
{
"items": [
{
"name": "item1",
"subItems": [
"name": "subItem1"
]
}
]
}

Categories