Why AngularJS $scope is not working correctly? - javascript

I'm new in AngularJS, I want to create an array and post it to server by register function, here's Controller code:
root.controller('mainController', function($scope) {
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data -> Array [ "1", "2", "3", "4", "1" ]
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array -> Array [ ]
};
});
Here's HTML code and directives:
<div class="container" ng-controller="mainController">
<a ng-click="register()"></a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add</a>
</div>
</div>
The problem occurs when i want to call register function, it gives me an empty array instead of array elements while it's not gonna happen in addItem function.

This is your code and work correctly.
var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
$scope.products = [{id:1},{id:2},{id:3},{id:4}];
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array
};
});
<div ng-app="testApp" ng-controller="testCtrl">
<a ng-click="register()">Register</a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add : {{product.id}}</a>
</div>
</div>

Related

Angular $scope is not available in the HTML Template but I can see it in console log?

I have been following some online tutorials and using the angularjs-template to get started with Angular. I can't get the page (html template) to update with the controller. I think there is a problem with the way I have set up the controller as the values are not available to the html template.
I have been trying to follow some of the best practive guides which suggested to wrap my components in an 'Invoked Function Expression' and to seperate out the controller, service and service manager. However, I think I have made a bit of a hash of this and need some help to figure out what I am doing wrong.
With the console I can see that $scope.metric contains the information I want. For me this means that the controller has successfully pulled the data back from my API via the metricService. However I can't seem to have the results printed back onto the html page e.g. metric.id.
Any help appreciated - I am at the end of my wits trying to figure this out.
metric.html
<div class="panel panel-primary">
<div class="panel-body">
<!-- Try First Way to Print Results -->
Id: <span ng-bind="metric.id"></span></br>
Name:<input type="text" ng-model="metric.metadata.name" /></br>
<!-- Try Second Way to Print Results -->
<p data-ng-repeat="thing in ::MEC.metric track by $index">
{{$index + 1}}. <span>{{thing.metadata.name}}</span>
<span class="glyphicon glyphicon-info-sign"></span>
</a>
</p>
<!-- Try Third Way to Print Results -->
Id: <span ng-bind="Metric.metricId"></span></br>
Id: <span ng-bind="Metric.id"></span></br>
Id: <span ng-bind="metricService.id"></span></br>
<!-- Try Fourth Way to Print Results -->
Id: <strong>{{::MEC.metric.id}}</strong></br>
Name: <strong>{{::MEC.metric.metadata.name}}</strong></br>
Height: <strong>{{::MEC.metric.type}}</strong>
</div>
metricController.js
(function () {
'use strict';
angular.module('app.metric', ['app.metricService', 'app.metricManager'])
.controller('MetricController', MetricController)
MetricController.$inject = ['$scope', 'metricManager', '$log'];
function MetricController($scope, metricManager, $log) {
metricManager.getMetric(0).then(function(metric) {
$scope.metric = metric
$log.info('$scope.metric printed to console below:');
$log.info($scope.metric);
})
}
})();
metricService.js
(function () {
'use strict';
angular.module('app.metricService', [])
.factory('Metric', ['$http', '$log', function($http, $log) {
function Metric(metricData) {
if (metricData) {
this.setData(metricData);
}
// Some other initializations related to book
};
Metric.prototype = {
setData: function(metricData) {
angular.extend(this, metricData);
},
delete: function() {
$http.delete('https://n4nite-api-n4nite.c9users.io/v1/imm/metrics/' + metricId);
},
update: function() {
$http.put('https://n4nite-api-n4nite.c9users.io/v1/imm/metrics/' + metricId, this);
},
hasMetadata: function() {
if (!this.metric.metadata || this.metric.metadata.length === 0) {
return false;
}
return this.metric.metadata.some(function(metadata) {
return true
});
}
};
return Metric;
}]);
})();
metricManager.js
(function () {
'use strict';
angular.module('app.metricManager', [])
.factory('metricManager', ['$http', '$q', 'Metric', function($http, $q, Metric) {
var metricManager = {
_pool: {},
_retrieveInstance: function(metricId, metricData) {
var instance = this._pool[metricId];
if (instance) {
instance.setData(metricData);
} else {
instance = new Metric(metricData);
this._pool[metricId] = instance;
}
return instance;
},
_search: function(metricId) {
return this._pool[metricId];
},
_load: function(metricId, deferred) {
var scope = this;
$http.get('https://n4nite-api-n4nite.c9users.io/v1/imm/metrics/' + metricId).then(successCallback, errorCallback)
function successCallback(metricData){
//success code
var metric = scope._retrieveInstance(metricData.id, metricData);
deferred.resolve(metric);
};
function errorCallback(error){
//error code
deferred.reject();
}
},
/* Public Methods */
/* Use this function in order to get a metric instance by it's id */
getMetric: function(metricId) {
var deferred = $q.defer();
var metric = this._search(metricId);
if (metric) {
deferred.resolve(metric);
} else {
this._load(metricId, deferred);
}
return deferred.promise;
},
/* Use this function in order to get instances of all the metrics */
loadAllMetrics: function() {
var deferred = $q.defer();
var scope = this;
$http.get('ourserver/books')
.success(function(metricsArray) {
var metrics = [];
metricsArray.forEach(function(metricData) {
var metric = scope._retrieveInstance(metricData.id, metricData);
metrics.push(metric);
});
deferred.resolve(metrics);
})
.error(function() {
deferred.reject();
});
return deferred.promise;
},
/* This function is useful when we got somehow the metric data and we wish to store it or update the pool and get a metric instance in return */
setMetric: function(metricData) {
var scope = this;
var metric = this._search(metricData.id);
if (metric) {
metric.setData(metricData);
} else {
metric = scope._retrieveInstance(metricData);
}
return metric;
},
};
return metricManager;
}]);
})();
Snippet from App.routes
.state('root.metric', {
url: 'metric',
data: {
title: 'Metric',
breadcrumb: 'Metric'
},
views: {
'content#': {
templateUrl: 'core/features/metric/metric.html',
controller: 'MetricController',
controllerAs: 'MEC'
}
}
})
Console
You are mixing two concepts controller alias and $scope, in your case you are creating controller alias as MEC using controllerAs. If you are using controller alias then this will work fine for you :
function MetricController($scope, metricManager, $log) {
var MEC = this;
metricManager.getMetric(0).then(function(metric) {
MEC.metric = metric
$log.info('$scope.metric printed to console below:');
$log.info($scope.metric);
})
}
If you don't want to use controller alias and share data between view and controller via $scope then in your view you should use something like this {{::metric.metadata.name}} and controller function should stay as it is.
PS: If you are using alias then MEC in var MEC = this can be MEC or abc or any name you like but convention is to use var vm = this and controllerAs: 'vm'. If you have controllerAs: 'xyz' then in your view xyz should be used to access model.
Problem with your view HTML, you need to use proper Angular expressions while binding. When you want use ::MEC alias name you need to mark your controller with as keyowrd, like ng-controller="xyz as MEC". And checkout working Plunker
<div class="panel panel-primary">
<div class="panel-body">
<!-- Try First Way to Print Results -->
Id: <span ng-bind="metric.id"></span>
<br> Name1:
<input type="text" ng-model="metric.metadata.name" />
<br><br><br><br>
<!-- Try Second Way to Print Results -->
<p data-ng-repeat="thing in [metric] track by $index">
{{$index + 1}}. <span>{{thing.metadata.name}}</span>
<span class="glyphicon glyphicon-info-sign"></span>
</p><br><br><br>
<!-- Try Third Way to Print Results -->
Id: <span ng-bind="metric.metricId"></span>
<br> Id: <span ng-bind="metric.id"></span>
<br><br><br>
<!-- Try Fourth Way to Print Results -->
Id: <strong>{{::metric.id}}</strong>
<br> Name: <strong>{{::metric.metadata.name}}</strong>
<br> Height: <strong>{{::metric.type}}</strong>
</div>
</div>

data is lost after page refresh from local storage

i am storing user info into local storage, but every time i reload the page data is lost. not getting the exact solution. Here is my js code. i am getting value for user object from html in this format
{"fname":"A","lname":"B","age":"12","email":"a#b.com","class":"6","password":"1234"}
here is my js code
var app = angular.module("myApp",["ngStorage"]);
app.controller("myCtrl", function($scope,$localStorage,
$sessionStorage) {
var usersinfo= [];
$scope.submit = function() {
usersinfo.push($scope.user);
localStorage.setItem("usersinfo", JSON.stringify(usersinfo));
console.log(usersinfo);
};
});
You are importing $localStorage and using localStorage.
See documentation for read/write syntax.
The following example works fine when executed separately in an HTML file (Dont expect it to load localStorage in StackOverflow execution environment)
var user = {
"fname": "A",
"lname": "B",
"age": "12",
"email": "a#b.com",
"class": "6",
"password": "1234"
};
var app = angular.module("app", []);
app.controller("MyController", function($scope) {
console.log('Loaded');
$scope.usersinfo = [];
$scope.show = function() {
$scope.usersinfo = JSON.parse(localStorage.getItem('usersinfo'));
console.log($scope.usersinfo)
};
$scope.submit = function() {
$scope.usersinfo.push(user);
localStorage.setItem("usersinfo", JSON.stringify($scope.usersinfo));
console.log($scope.usersinfo);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<p>Hi</p>
<button type="button" ng-click="submit()">Submit</button>
<button type="button" ng-click="show()">Show</button>
<p>{{usersinfo}}</p>
</div>
</div>

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

AngularJS data model architecture

I have the following thing on my Angular app:
$scope.things = [{
title: 'Simple',
type: 1,
form: {
input: [1, 2, 3],
clone: true
}
}];
$scope.clone = function(item) {
item.form.input.push(Math.floor(Math.random() * 999));
};
And on the HTML part:
<div ng-repeat="item in things" class="item">
<h2>{{item.title}}</h2>
<div ng-repeat="input in item.form.input">
<input type="text" />
</div>
<button ng-click="cloneInput(item)">Clone</button>
</div>
When press the Clone button I'm pushing a new element to form.input array and add a new input to the DOM.
I want to $http.post all the values for the inputs.
I know to push something I need to use
$http.post('/path/to/my/api', {my object}).callback()
But I dont know how to make an object from all the .item inputs.
Can someone explain me how or suggest a better solution?
If you use a ng-model for your inputs and set it to an object you can then inject that object to the post, here is a really basic example:
JSFiddle
HTML:
<div ng-app="myApp" ng-controller="dummy">
<div ng-repeat="input in items">
<input type="text" name="{{input.name}}" ng-model="data[input.name]" />
</div>
<button ng-click="submit()">Submit</button>
<p ng-show="displayIt">{{data}}</p>
</div>
JS:
angular.module('myApp', [])
.controller('dummy', ['$scope', function ($scope) {
$scope.items = [{
name: 'test'
}, {
name: 'test2'
}];
$scope.data = {};
$scope.displayIt = false;
$scope.submit = function () {
// This is only to check it
$scope.displayIt = true;
// Do your post here
};
}]);

AngularJS dynamically populate details from json based on item selected

I am trying to create a page where you have few items in a list group which when selected should show more details.
Please view the example here http://plnkr.co/edit/Oava3pA9OTsm80K58GdT?p=preview
How can I populate the details from the json file based on the item that is selected in the list group?
This is what I have so far.
html:
<div ng-controller=ItemsController>
<h3>Test</h3>
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<ul class="list-group">
<a class="list-group-item" ng-repeat="item in itemDetails">{{item.name}}</a>
</ul>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<h2>Name: </h2>
<br />Address Line 1:
<br />Address Line 2:
<br />Suburb:
<br />Phone:
<br />Email:
</div>
</div>
</div>
</div>
script:
var myItemsApp = angular.module('myItemsApp', []);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory ={
itemDetails: function() {
return $http(
{
url: "mockItems.json",
method: "GET",
})
.then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory', function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
}]);
json:
[
{
"$id":"1",
"name":"Test itemName 1",
"themeName":"ASD",
"addressLine1":"18 Banksia Street",
"addressLine2":null,
"suburb":"Heidelberg",
"state":"VIC",
"postalCode":"3084",
"contactPhone":"+61 3 123456",
"emailAddress":"qwerty.it#xyz.com"
},
{
"$id":"2",
"name":"Test itemName 2",
"themeName":"WER",
"addressLine1":"11 Riverview Place",
"addressLine2":"Metroplex on Gateway",
"suburb":"Murarrie",
"state":"QLD",
"postalCode":"4172",
"contactPhone":"1300 73123456",
"emailAddress":"asdfg.it#xyz.com"
},
{
"$id":"3",
"name":"Test itemName 3",
"themeName":"ERT",
"addressLine1":"60 Waterloo Road",
"addressLine2":null,
"suburb":"North Ryde",
"state":"NSW",
"postalCode":"2113",
"contactPhone":"123456",
"emailAddress":"zxcvb.it#xyz.com"
}
]
Any help would be greatly appreciated.
I am very new to programming. Please also feel free to alternative ways of achieving this if I have done it wrong.
You can use the ng-click directive to specify what happens when you click something.
So I made it assign the clicked item to the $scope.selected object using a function ($scope.select(item)) and then I bound the properties of that object to your little details section. That's probably the simplest way to do it.
Ctrl
$scope.select = function(item) {
$scope.selected = item;
}
$scope.selected = {};
HTML
<a class="list-group-item" ng-click="select(item)" ng-repeat="item in itemDetails">
{{item.name}}
</a>
And the selected object is then available like this:
<h2>Name: {{selected.name}}</h2>
etc...
See my example here: http://plnkr.co/edit/mUMZ0VGO8l1ufV1JJNQE?p=preview

Categories

Resources