Angularjs Function in Controller scope - function

I have a strange thing:
my controller works, but getHash service is called on loading, instead on calling saveit() function on index html:
angular.module('myApp.controllers', [])
.controller('MyCtrl', ['$scope','$http','getHash', function ($scope,$http, getHash) {
$scope.keys = getHash.get(function(keys) {
$scope.key = keys.key;
});
$scope.saveit = function () {
$scope.formData = {
'key' : $scope.key
};
console.log ($scope.formData);
//Do Something with formData
}
}
This Example is not working, the $scope.key is empty, but the getHash Service is called as it should.
angular.module('myApp.controllers', [])
.controller('MyCtrl', ['$scope','$http','getHash', function ($scope,$http, getHash) {
$scope.saveit = function () {
$scope.keys = getHash.get(function(keys) {
$scope.key = keys.key;
});
$scope.formData = {
'key' : $scope.key
};
console.log ($scope.formData);
//Do Something with formData
}
}
Has anyone an explanation for this behavior? how can i get $scope in the function saveit?
or save variables to $scope inside saveit?
Thanks, Patrick

Related

How to create function to get data from WCF Rest then display to table

I have declare function to get WCF Rest the name is service.js, the url get Json data. Then I create another function to get data entryCtrl.js then show to html
service.js
(function (app) {
app.service("CRUD_AngularJs_RESTService", function ($http) {
this.getAllEntry = function () {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetAllRequest/");
};
});
})(angular.module('model'));
entryCtrl.js
(function (app) {
'use strict';
app.controller('entryCtrl', entryCtrl);
entryCtrl.$inject = ['$scope'];
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
$scope.GetAllRecords = function() {
var promiseGet = CRUD_AngularJs_RESTService.getAllEntry();
promiseGet.then(function (pl) { $scope.EntryData = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
}
})(angular.module('model'));
view entry.html
<table data-ng-controller="entryCtrl">
<tbody data-ng-repeat="entry in EntryData">
<tr>
<td>{{entry.name}}</td>
<td>{{entry.telpon}}</td>
<td>{{entry.foobar}}</td>
</tr>
</tbody>
</table>
I don't have any error, my data in table not show anything. What must I try to know the function it's work or not?
jush have warning XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. I don't know what it is mean.
The function GetAllRecords() is not set to the $scope. You need to set $scope.GetAllRecords = GetAllRecords before the call to $scope.GetAllRecords():
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
$scope.GetAllRecords = function() {
var promiseGet = CRUD_AngularJs_RESTService.getAllEntry();
promiseGet.then(function (pl) { $scope.EntryData = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
$scope.GetAllRecords();
}
Alternatively, you can simply call GetAllRecords() directly, since you don't seem to need it in the $scope:
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
(function() {
var promiseGet = CRUD_AngularJs_RESTService.getAllEntry();
promiseGet.then(function (pl) { $scope.EntryData = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
})();
}

External JSON File - IONIC

I use the Tab Template, with list of chats and chats detail. I've put the data into a json file, and add it like this in my code : $http.get("http://abcd/Chats.json").
The data are showing on the List of Chats, but it doesn't work on the Detail Page.
I've tested a lot of solution, but I'm still getting an error...
Here is my code:
SERVICE
angular.module('starter.services', [])
.factory('Chats', function($http) {
// Might use a resource here that returns a JSON array
return {
getChats: function() {
return $http.get("http://abcd/Chats.json").success(function(response){
chats=response;
return chats;
});
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
});
CONTROLLER
.controller('ChatsCtrl', function($scope, Chats) {
Chats.getChats().success(function(response){
$scope.chats =response;
});
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
} )
My error is: cannot read property of chat undefined..
Any help please?
Try to define chats as a var inside your factory.
.factory('Chats', function($http) {
var chats;
...

Angular: Directive watch model defined in own controller

I try to update my chart when data is pushed to a websocket. I want to do this by defining my own directive in angular, but the binding of data does not work. The Code:
angular.directive("myChart", ['service', function (service) {
function ChartController ($scope) {
var ws = new WebSocket("url/to/websocket/");
var data = service.initData(); // initialize data table
ws.onmessage = function (event) { // listen and update data
data = service.updateData(event.data);
$scope.recentData = data;
}
$scope.recentData = data;
}
function link(scope, element, attr) {
function drawChart (data) {}
scope.$watch('data', function (newD, old) {
drawChart(newD);
}, true);
}
return {link: link, controller: ['$scope', ChartController], restrict: 'EA'}
}
Thats a simplistic example, of what i want to do. The service and data changes work well, i can log the current values. However drawChart() gets called only on startup and not on every mutation.
The Controller has to be part of the directive and not wrapped around
You need to notify angular of the changes by using a method that calls apply() after the change occurs, which is preferably done by using $timeout.
angular.directive("myChart", ['service', '$timeout', function (service, $timeout) {
function ChartController ($scope) {
var ws = new WebSocket("url/to/websocket/");
var data = service.initData(); // initialize data table
ws.onmessage = function (event) { // listen and update data
data = service.updateData(event.data);
$scope.recentData = data;
}
$scope.recentData = data;
}
function link(scope, element, attr) {
function drawChart (data) {}
scope.$watch('data', function (newD, old) {
$timeout(function(){
drawChart(newD);
});
}, true);
}
return {link: link, controller: ['$scope', ChartController], restrict: 'EA'}
}

Displaying nested JSON with angularjs

I am trying to display nested JSON in a page. I'm not sure how to drill down into it.
In my app js file I have an parameter called initialData that I want to call a function getProducts() when the view is called...
'use strict';
var quoteApp = angular.module('quoteApp', ['ui.router']);
quoteApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'ng-views/choose.html',
controller: "quoteBuilderController",
resolve: {
initialData: ['quoteApi', function (quoteApi) {
return quoteApi.getProducts();
}]
}
})
});
my quoteApi looks like this in case you want to see it...
(function () {
'use strict';
angular.module('quoteApp').factory('quoteApi', quoteApi);
quoteApi.$inject = ['$http'];
function quoteApi($http) {
var service = {
getProducts: getProducts,
getPrices: getPrices
};
var baseUrl = 'http://www.website.com/api/Pricing';
return service;
function getProducts() {
return httpGet('/GetProductCatalogue');
}
function getPrices() {
return httpGet('/GetPrices');
}
/** Private Methods **/
function httpExecute(requestUrl, method, data){
return $http({
url: baseUrl + requestUrl,
method: method,
data: data,
headers: requestConfig.headers }).then(function(response){
return response.data;
});
}
function httpGet(url){
return httpExecute(url, 'GET');
}
}
})();
So quoteApi.getProducts() returns JSON that looks like this...
{
"Cat1": [
{
"product_id": 1,
"product_name": "Prod1"
},
{
"product_id": 2,
"product_name": "Prod2"
}
],
"Cat2": [
{
...
}
]
}
My controller for the view looks like this...
(function () {
'use strict';
angular.module('quoteApp').controller('quoteController', ['$scope', '$http', '$timeout', quoteController]);
quoteController.$inject = ['initialData', 'quoteApi'];
function quoteController($scope, initialData) {
$scope.cat1Products = initialData;
};
})();
So my question is, how can I get 'initialData' to load products from Cat1 only? Should I try to do this from the html? It seems like it should be straight forward enough but I can seem to get it. Thank you.
You need to transform your response from your http request further so you only return the piece you require, and you may also want to consider using the .then() approach:
$http.get('/someUrl').then(function(response) {
//Do something with response.data.Cat1 here
}, function(errResponse) {
console.error('Error while fetching data');
});
Just take out cat1 from your initialData object
function quoteController($scope, initialData) {
$scope.cat1Products = initialData['Cat1'];
};

to pass parameter to web api through ajax call

I have below ajax query which returns me json from controller
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=1",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
the controller action is as below
[System.Web.Http.ActionName("GetHomeTab")]
public HomeTabModel GetHomeTab(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new HomeTabModel
{
HomeDesc = outlet.BizHomeDesc,
HomeTabText = outlet.BizHomeTabText
};
}
Now my question is: curently i am sending hard coded value of bizId to web api. I want to send this value dynamically. How can i achieve this? I have that value in my route config file. The code is as below-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);
}
I am new to this. Please help! Thanks in advance!
no, actually after much research, i came up with this solution and this works fine for me....
In controller,
public ActionResult Index(int bizId)
{
ViewBag.BizId = bizId;
return View();
}
and in View,
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=#ViewBag.BizId",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
You can pass a data object as part of the GetJson call.
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab",{bizId : 1},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
Taking this one step further you could wrap this in a function.
function makeCall(id)
{
$.getJSON("api/OutletPOC/GetHomeTab",{bizId : id},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
}
Also look into using promises.
$.getJSON().then().done();