Angular JavaScript Update $scope variable onClick - angularjs

I'm trying to update a $scope variable onClick that populates a table from a local JSON file. So far my code is
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$scope.update = function () {
// Load JSON data to $scope
$http({
method: 'get',
url: '/JSON/Info.json'
}).then(function (response) {
console.log(response, 'res');
$scope.friendz = response.data[1];
},function (error){
console.log(error, 'can not get data.');
});
}
});
<div ng-controller="myCtrl" class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<button class="dropdown-item" ng-click="update()">Action</button>
</div>
<div ng-controller="myCtrl">
<table border="1">
<tr>
<th>Name</th>
<th>Fax</th>
<th>Phone</th>
<th>Address</th>
<th>Attention</th>
<th>Submission</th>
</tr>
<tr>
<td ng-bind="friendz.Payee.Name"></td>
<td ng-bind="friendz.Payee.Fax"></td>
<td ng-bind="friendz.Payee.Phone"></td>
<td ng-bind="friendz.Payee.Address"></td>
<td ng-bind="friendz.Payee.Attention"></td>
<td ng-bind="friendz.Payee.SubmissionDate"></td>
</tr>
</table>
</div>
When I click my update button in the dropdown menu, I see the response is logged in the console, but the table fails to update onClick. Is there a function that I need to call to update the page in an asynchronous fashion when I click my button? When I use the http get function outside of my scope.update function, it works fine on page load.

You're creating two separate instances of your controller, since you have ng-controller="myCtrl" twice in the template.
So he controller handling the click is not the same one that holds the data displayed by the table. And their scope are not the same either: each controller instance has its own scope.

Related

Angular why doesn't work nested ng-repeat

I use nested ng-repeat to loop in all objects values.
<tr class="" ng-repeat="(position, values) in chartResult.realData track by $index">
<td>
<div ng-click="select(position)" ng-class="{selected: position===selectedItem}">
<a href ng-click="select(position)">
<span>{{position}}</span>
</a>
</div>
</td>
<td ng-repeat="val in values">
{{val}}
</td>
</tr>
Why nested loop doesn't work?
Updated
app.controller('Ctrl',['$log', '$rootScope', '$scope', '$http', '$timeout',
function ($log, $rootScope, $scope, $http, $timeout) {
$http({
//request
}).then(
function successCallback(response) {
//after parse response realData view something like this
var res = {realData:
name1:[1,2,4,0,1,23],
name2:[4,6,3,7,2,3],
...
}
$scope.chartResult = res;
}
}]);
After add track by $index to nested loop it work as well.
If you pasted it correctly realData is not an array.
But please show us what is in the realData.

Angular $resource returns TypeError

Hello I am trying to get a url from my api using the ngResource and I have a service that returns the resource. However when I call it inside my controller is gives me an error of Cannot read property 'query' of undefined.
Why is this happening?
This is my service :
(function() {
var app = angular.module('test');
app.service('ContactResource', ['$resource', function($resource) {
return $resource('/contacts/:firstname', {firstname: '#firstname'},
{
'update': {method: 'PUT'}
}
);
}]);
}());
This is my controller
(function() {
var app = angular.module('test');
app.controller('contactsCtrl', ['ContactResource', function($scope, Contacts, ContactResource) {
$scope.contacts = ContactResource.query();
}]);
}());
And this is my HTML
<table class="table table-bordered">
<thead>
<th>Firstname <input type="search" class="pull-right"></th>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>
<a ng-href="/{{ contact.firstname }}">{{ contact.firstname }}</a>
</td>
</tr>
</tbody>
</table>
Here is your problem:
['ContactResource', function($scope, Contacts, ContactResource)
You need to also inject $scope and Contacts into the array, like this:
['$scope', 'Contacts', 'ContactResource', function($scope, Contacts, ContactResource)
Or Angular will think that 'ContactResource' is the same as $scope.

Controller is not a function, got undefined

I'm trying to create a directive on a controller. The directive will create a table of items returned from djangorestframework.
controller.js:
var expensesApp = angular.module('expensesApp', []);
expensesApp.controller('ShoppingListController', ['$scope', '$http',
function($scope, $http){
$http(
{
method: 'GET',
url: '/items/?format=json'
})
.success(function(data, status, headers, config) {
$scope.items = data;
})
.error(function(data, status, headers, config) {
});
}]);
directive.js
angular.module('expensesApp', [])
.directive('shoppingList', function () {
return {
restrict: 'A',
templateUrl: 'http://localhost:8000/static/angular/partials/shopping-list.html',
controller: 'ShoppingListController'
};
})
The partial being pulled in by the directive:
shopping-list.html
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SHOP</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>[[ item.id ]]</td>
<td>[[ item.name ]]</td>
<td>[[ item.shop ]]</td>
</tr>
</tbody>
</table>
and the main html page where I define the app and the controller.
items.html
...
<div class="container" ng-app="expensesApp">
<div class="row">
<div class="col-md-6" ng-controller="ShoppingListController">
<div shopping-list></div>
</div>
</div>
</div>
...
The headers of the table in the partial are being pulled into the page, but it's not executing the $http and fetching the items that should make up the content of the table. I get ShoppingListController not a function, got undefined
Everything works if I don't split the table out into a directive. All items are returned and I don't see the error in the console.
Anyone have any idea what I'm doing wrong?
You are redefining module when you create a directive. It should be:
angular.module('expensesApp')
.directive('shoppingList', function () {
return {
restrict: 'A',
templateUrl: 'http://localhost:8000/static/angular/partials/shopping-list.html',
controller: 'ShoppingListController'
};
});
If you pass an array as the second argument to module method angular.module('expensesApp', []), Angular creates a new module without ShoppingListController controller in it. You should use getter syntax angular.module('expensesApp') to retrieve previously created module.

how to access data from scope object

I need to get data from $scope.List2 object:
<div ng-app="App">
<div id="firstlist" ng-controller="Controller">
<table id="requesttable" class="RequestTable">
<tr ng-repeat="item2 in List2">
<td class="selectedItem">{{item2.Title}}</td>
</tr>
</table>
<button id="Reqbutton" onclick="SendRequest()">Send</button>
</div>
</div>
The problem is that if I put SendRequest function inside controller then it cannot be called (I get "SendRequest() is not defined" message). And if I put the function outside the controller I cannot access List2.
What do I miss?
As #sp00m suggested. You should use ng-click instead of onclick on the button. The html would look like this then:
<button id="Reqbutton" ng-click="sendRequest()">Send</button>
In your controller
app.controller('testController', ['$scope', function {
$scope.list2 = [];
$scope.sendRequest = function() {
var test = $scope.list2;
...
};
}]);

Can an Angular JS template contain a controller?

Here's my route...
angular.module('ng').
config(function ($routeProvider) {
$routeProvider.
when('/User_View', { templateUrl: '/rest/tbot/run/User_View' });
});
In the template it has the following...
<div ng-controller="TMUser">
TMUser is defined in the template in a script block. But the code in the controller doesn't appear to run. Why is this?
The controller shouldn't be defined in the template file. I don't think Angular can know about it and load it that way. Define it in a code file that will be executed before the route change happens.
You can also specify the controller in the routeProvider configuration object, like:
when('/User_View', { templateUrl: '/rest/tbot/run/User_View', controller:'TMUser' });
This fiddle demonstrates a very simple example (source)
Above answer is correct.
But i achived the same thing using ng-include and ng-hide, what exactly ng-view and routing does.
I have created a partial page without controller and included that in parent page and made that partial page hidden after a button click i am just displaying the page.
Routing has there on benifit. you can pass the paramter and change the view accordingly ang browser history.
here is my page conatins below code inside a child controller.
<span ng-include="'/PartialPages/ChangeDetails.htm'"></span>
which refers my parital page
<div id="ChangeInfo" ng-show="datashow">
<table width="100%">
<thead>
<tr>
<th>File Name</th>
<th>File Create Date</th>
<th>File Modified Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="file in FilesDetails" ng-class="{TableStrip : ($index % 2)}">
<td>{{file.FileName}}</td>
<td>{{file.CreateDate}}</td>
<td>{{file.ModifiedDate}}</td>
</tr>
</tbody>
</table>
<hr />
</div>
and the controller code
var deploymentVerifierModule = angular.module("DeploymentVerifierApp", ['DeploymentServiceModule']);
deploymentVerifierModule.controller("DeploymentVerifierCntrl", function ($scope, DeploymentService) {
$scope.datashow = false;
$scope.PleaseWait = false;
$scope.VerifyChange = function () {
//Get the Change ticket number from textbox
$scope.PleaseWait = true;
var changeticketnum = document.getElementById("ChangeNumber").value;
DeploymentService.GetChangeDetails(changeticketnum).then(function (data) {
$scope.FilesDetails = angular.fromJson(data);
$scope.PleaseWait = false;
$scope.datashow = true;
}, function (error) { });
};
});
still i did not get some of your point why do you want controller to be in template. and templateurl property contains the extenstion of page also.

Resources