Can't pass ID and call Controller from ajax or AngularJS - javascript

I have a table of objects, and I want to pass their ID on click, and without refresh populate a div or table, I've tried with AJAX and angular but can not pass ID.
If I fix the ID on a specific number it works.
In the View:
<script>
function CountryController($scope, $http) {
$http.get("/api/SportApi/GetCountry/").success(function (response) {
$scope.controllerFunction = function (value) {
console.log(value);
}
obj = JSON.parse(response);
$scope.country = angular.fromJson(obj);
});
}
</script>
<a class="item item-thumbnail-left" ng-href="#/api/SportApi/GetCountry/{{x.id}}" ng-click="CountryControler(x.id)">
click for countries
</a>

Could you try this:
function CountryController($scope, $http, id) {
console.log(id)
$http.get("/api/SportApi/GetCountry/").success(function (response) {
$scope.controllerFunction = function (value) {
console.log(value);
}
obj = JSON.parse(response);
$scope.country = angular.fromJson(obj);
});
}

On your view, you should have:
<a class="item item-thumbnail-left" href ng-click="CountryControler(x.id)">click for countries</a>
where href will stop the link from reloading the page and the ng-click will call a method on your controller.
In your controller, you should define that function on the scope variable:
var myApp = angular.module('myApp',[]);
myApp.controller('ExamleController', ['$scope', function($scope) {
$scope.CountryController = function(id) {
$http.get("/api/SportApi/GetCountry/" + id).success(function (response) {
$scope.controllerFunction = function (value) {
console.log(value);
}
obj = JSON.parse(response);
$scope.country = angular.fromJson(obj);
});
}
}]);
Verify that you have bootstrapped angular js (by defining the root element of your html with ng-app).
Verify that you have attached the controller class to your view (by defining the controller html element with ng-controller).
You should also verify that you are getting the right id on the view when calling "x.id".
$scope.controllerFunction seems unnecessary in this case.

Related

Handle multiple item in single controller? AngularJS

I am relatively new to Angular JS. Currently I met a problem, lets say I have 1000 items in a list. In order to display the details about each item I will pass the items_id to generate html example(123.html). In this case, do I need 1000 controller to handle this kind of situation?
Controller
app.controller('item0001',function($scope,$http,$sce){
$scope.data = [];
$scope.details=[];
$http.get("https://api.com/test/product/0001").then(function(response){
var getData = response.data;
$scope.data.push(response.data);
$scope.bindHtml = $sce.trustAsHtml(getData.details);
for(var i = 0; i<getData.specification.length; i++){
$scope.details.push(getData.details[i]);
}
});
});
app.controller('item0002',function($scope,$http,$sce){
$scope.data = [];
$scope.details=[];
$http.get("https://api.com/test/product/0002").then(function(response){
var getData = response.data;
$scope.data.push(response.data);
$scope.bindHtml = $sce.trustAsHtml(getData.details);
for(var i = 0; i<getData.specification.length; i++){
$scope.details.push(getData.details[i]);
}
});
});
View
<p>
View More
</p>
Use single controller and HTML.
Bind the HTML with some ViewModel (a property on $scope)
From your controller place the call to fetch item details (I am assuming you have fetch these details on click of some button) using a service.
In success callback of your service update the view model. and angular using 2-way binding, will update the view with last item fetched.
Controller:
app.controller('ProductCtrl', function($scope, ProductService) {
var getProduct = function(productId) {
ProductService.getProduct(productId).then(function(response) {
$scope.productDetails = response.data;
})
};
});
Service:
app.factory('ProductService', function($http) {
return {
getProduct(productID) {
return $http({
method: 'GET',
url: "https://api.com/test/product/" + productID
});
};
}
});
HTML View:
<body ng-controller="ProductCtrl">
<div ng-init="getProduct(0001)">
<p>Name {{productDetails.name}}</p>
<p>ID {{productDetails.id}}</p>
<p>Description {{productDetails.description}}</p>
</div>
<button ng-click="getProduct(productDetails.id + 1)">Get Next Product</button>
</body>
I hope this gives you a basic idea of how to implement your requirement. Please elaborate your question so that I can provide a more specific solution.
Define a single view (html) and controller to handle this.. example below.
productDetails.html (view)
<div>
<span>{{productName}}</span>
</div>
productDetails.js (controller)
app.controller('productDetailsCtrl',function($scope,$http,$sce){
$scope.productName = "";
$http.get("https://api.com/test/product/0001").then(function(response){
var getData = response.data;
$scope.productName = getData.productName;
});
});

angularjs: how to store the function returning value in one variable . based on ng-repeat

hi i am getting the intrestedid from ng-repeat , i want to call another service and store that data in one variable dynamically , because need send seperate api for getting images.
my html is look like this
<div class="" ng-repeat="item in items" >
<div ng-init="MyPic = getMyprofile(item.interestedTo)">
<img src="{{MyPic}}">
</div>
</div>
My controller is look like this.
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
My services is look like this.
service.profile= function(userId, callback) {
path = serviceUrl + '/profile/'+ userId;
$http({
method: 'GET',
url: path
}).then(function(data) {
callback(data)
}, function(data) {});
}
but its getting undefined , any issues in this code.
I tried to resolve this by creating some abstract stub, that may be helpful to you. Please review and let me know if issue still arise
HTML
<div ng-repeat ="data_ in parentData track by $index">
<ul>
<li ng-repeat="result in data_.data track by $index" ng-init="counter=increaseCounter();">
<div ng-model="counter"></div>
</ul>
</div>
Controller
// It simply store variable value in scope.counter
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
return cnt;
};
//Another way is to call service while update variable vaule
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
AppService.updateValue(cnt);
return cnt;
};
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
I think issue is this function. appService.profile is asyncronize method and before complete it function return $scope.meDetails;
my suggestion is to hardcore some value like in below and see the result. if it is working then you have to change the function accordingly.
$scope.meDetails ='some value';
return $scope.meDetails;
There are several best practice issue along with the async problem.
1.Avoid using ng-init unless you want to re-run the function when you reconstruct the element, for instance ng-if. It is more so when you use ng-repeat without track by, any changes in the data source would re-trigger all ng-init in the children.
Solution: Run them when you init the controller, or as soon as $scope.items is filled.
angular.forEach($scope.items, function(item) {
appServices.profile(item).then(function(data){
item.myPic = data;
});
});
<div class="" ng-repeat="item in items" >
<img src="{{item.myPic}}">
</div>
2.The correct way to wrap a function that returns promise (which $http is) is to return the function itself. You can research more on how to pass the resolved/rejected result around.
// not needed anymore, just to showcase
$scope.getMyprofile = function(IntrstdId){
return appServices.profile( IntrstdId );
}
// same goes with the service function
service.profile= function(userId) {
path = serviceUrl + '/profile/'+ userId;
return $http({
method: 'GET',
url: path
}).then(function(response) {
return response.data;
});
}

Accessing ng-hide value of one controller to manipulate ng-style of another controller within a global controller

So I am trying to access the boolean value of ng-hide from one controller to change css properties of another controller using a global controller. Here is the link on jsfiddle: https://jsfiddle.net/dqmtLxnt/
HTML
<div ng-controller="mainCtrl">
<div class="first" ng-style="changeColor" ng-controller="firstCtrl">
{{ accessOne }}
</div>
<div class="second" ng-hide="hideSecond" ng-controller="secondCtrl">
{{ accessTwo }}
</div>
</div>
JS
angular.element(document).ready(function() {
angular.module('app', [])
.controller('mainCtrl', ['$scope', function($scope) {
if ($scope.hideSecond == true) {
$scope.changeColor = {
'color': 'blue'
};
}
}]).controller('firstCtrl', ['$scope', function($scope) {
$scope.accessOne = "One";
}]).controller('secondCtrl', ['$scope', function($scope) {
$scope.accessTwo = "Two";
$scope.hideSecond = true;
}]);
angular.bootstrap(document.body, ['app']);
});
I am able to change both changeColor and hideSecond from mainCtrl but I'm not able to access the value set from secondCtrl in the mainCtrl. I even tried setting hideSecond=true in ng-hide and access it on mainCtrl but to no avail.
Can someone help me on this?
You can use a Angular Service for this, storing the value into a service and than retrieving it from the service in another controller.
In your situation the main controller is loaded before the second controller so it would never know when the value is updated. You can use $watch for this, calling an update function when the $scope is updated.
Here if your fiddle updated: https://jsfiddle.net/dqmtLxnt/2/
Service:
angular.module('app.services', [])
.factory('hide', function() {
// Allows for passing of data between controllers
var x = false;
// Sets savedData to what ever is passed in
function set(data) {
x = data;
}
// Returns saved data
function get() {
return x;
}
return {
set: set,
get: get
}
})
Using it in Main Controller:
$scope.$watch(function () { return hide.get(); },
function (value) {
console.log(value);
$scope.update(value);
});
$scope.update = function(value) {
if (value == true) {
$scope.changeColor = {
'color': 'blue'
};
}
}
Using it in Second Controller:
$scope.hideSecond = true;
hide.set(true);
Make sure you inject the service into the app and the service into the controllers.

Ng-model with Cookie

I'm trying to take the first example from the angular.js homepage and adding in cookie support.
This is what I have so far: https://jsfiddle.net/y7dxa6n8/8/
It is:
<div ng-app="myApp">
<div ng-controller="MyController as mc">
<label>Name:</label>
<input type="text" ng-model="mc.user" placeholder="Enter a name here">
<hr>
<h1>Hello {{mc.user}}!</h1>
</div>
</div>
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', [function($cookies) {
this.getCookieValue = function () {
$cookies.put('user', this.user);
return $cookies.get('user');
}
this.user = this.getCookieValue();
}]);
But it's not working, ive been trying to learn angular.
Thanks
I'd suggest you create a service as such in the app module:
app.service('shareDataService', ['$cookieStore', function ($cookieStore) {
var _setAppData = function (key, data) { //userId, userName) {
$cookieStore.put(key, data);
};
var _getAppData = function (key) {
var appData = $cookieStore.get(key);
return appData;
};
return {
setAppData: _setAppData,
getAppData: _getAppData
};
}]);
Inject the shareDataService in the controller to set and get cookie value
as:
//set
var userData = { 'userId': $scope.userId, 'userName': $scope.userName };
shareDataService.setAppData('userData', userData);
//get
var sharedUserData = shareDataService.getAppData('userData');
$scope.userId = sharedUserData.userId;
$scope.userName = sharedUserData.userName;
Working Fiddle: https://jsfiddle.net/y7dxa6n8/10/
I have used the cookie service between two controllers. Fill out the text box to see how it gets utilized.
ok, examined your code once again, and here is your answer
https://jsfiddle.net/wz3kgak3/
problem - wrong syntax: notice definition of controller, not using [] as second parameter
If you are using [] in controller, you must use it this way:
myApp.controller('MyController', ['$cookies', function($cookies) {
....
}]);
this "long" format is javascript uglyfier safe, when param $cookies will become a or b or so, and will be inaccessible as $cookies, so you are telling that controller: "first parameter in my function is cookies
problem: you are using angular 1.3.x, there is no method PUT or GET in $cookies, that methods are avalaible only in angular 1.4+, so you need to use it old way: $cookies.user = 'something'; and getter: var something = $cookies.user;
problem - you are not storing that cookie value, model is updated, but cookie is not automatically binded, so use $watch for watching changes in user and store it:
$watch('user', function(newValue) {
$cookies.user = newValues;
});
or do it via some event (click, submit or i dont know where)
EDIT: full working example with $scope
https://jsfiddle.net/mwcxv820/

Can't get the datas in angularJs

I have html page like
<div ng-controller="userListControl">
...
</div>
<div ng-controller="userDetailsControl">
....
</div>
And i have angular Js code is
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", ['$scope','$http', function($scope, $http)
{
$http.get('data/userData.json').success (function(data){
$scope.users = data;
$scope.users.doClick = function(user,event) {
userInfo(user);
}
});
}]);
function userInfo(users)
{
console.log(user);
userDirectory.controller("userDetailsControl", function($scope)
{
console.log('well')
$scope.user = users;
console.log($scope.user)
});
}
Here Everything is working fine. But when we are calling click event, That userInfo called with particular Data. But Second controller gives an error(angular js Error).
I am new one in angular jS. I dont know this logic is correct or not.
I have list items in first Controller. When we are clicking on list, It gets data from particular list and passed to another design. That design have detailed data. So the 2nd controller shows particular list detailed Section
First, There is no need to declare your controller inside a function - I don't think that you're trying to lazy-load controllers. Make it available to your app when it starts.
Second, you need to pass data to the userDetailsControl controller. There are various ways to do this, but here you could just use the $rootScope.
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", function($scope, $rootScope, $http)
{
$scope.selectUser = function(user){
$rootScope.selectedUser = user;
}
$http.get('data/userData.json')
.success (function(data){
$scope.users = data;
});
})
.controller("userDetailsControl", function($scope, $rootScope){
$rootScope.$watch("selectedUser", function(newVal){
$scope.user = newVal;
}
}
and in your HTML:
<div ng-controller="userListControl">
<button ng-repeat="user in users" ng-click="selectUser(user)">{{user.name}}</button>
</div>
<div ng-controller="userDetailsControl">
<div>{{user.name}}</div>
<div>{{user.otherDetails}}</div>
</div>

Categories

Resources