Why Angular js Service does not work? - angularjs

I wrote script to test passing variables between controllers, so i define a service and declare variable on it getContents, then pass it to next controller personController, but something goes wrong, this is my script:
<script>
angular.module("app", []).service("personService", function () {
var getContents = {};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.getContents = data;
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
$scope.GetContent();
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
what is wrong?
NOTE: when i remove the Service, the controller work properly and get data from /Home/Get.
Edit: this is my edit:
<script>
angular.module("app", []).service("personService", function () {
var Content = {};
return {
getContent: function () {
return Content;
},
setContent: function (value) {
Content = value;
}
};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
debugger;
$http.get("/Home/Get").success(function (data) {
debugger;
console.log("successData :", data); //console did not log
personService.setContent(data);
console.log("ServiceData:",personService.getContent()) //console did not log too
$scope.Persons = data;
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
and this is my html:(for more help)
<div ng-app="app">
<div class="container" ng-controller="personController" ng-init=" GetContent()">
<div ng-show="!ShowForm">
<table class="table">
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in Persons">
<td>{{person.Name}}</td>
</tr>
</tbody>
</table>
</div>
</div>

you have to return service
service
angular.module("app", []).service("personService", function () {
var content = {};
var person = {
setContent :function(item){
content = item;
}
getContent : function(){
return content;
};
};
return person;
})
Controller
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.setContent(data); // set content to service..
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
personService.getContent(); // get content from service..
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
define personService.getContent() to $scope variable to display on view page.
$scope.content = personService.getContent();

Related

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

basic $scope connection with model

Its my code:
.controller("GetAllAuthors", function ($scope, $http) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
});
$scope.edit = function (index) {
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
}
})
Html view:
<tbody ng-repeat="author in authors">
<td><input type="button" ng-click="edit(author.id)" value="Edit"/></td>
<div ng-controller="GetAllAuthors">
{{object.id}} // <--- doesn't display it
</div>
It's not working. I can't use date binding with my object. How fix it?
You need to put http inside edit method.
.controller("GetAllAuthors", function ($scope, $http) {
$scope.edit = function (index) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
});
}
})
Try this
Initialize $scope.object outside the function.

Angular pass selected value from one drop-down to anouther using servises

I have two drop-downs and a table.
I don't know how exactly to pass the selected value from the first drop-down to the second. Except not passing selected value to the second drop-down the first service is working fine.
My JavaScript:
var myApp = angular.module("myApp", []);
myApp.service('companiesService', ['$http', '$q', function ($http, $q) {
var currentSettings = null;
this.getList = function () {
var def = $q.defer()
if (currentSettings) {
def.resolve(currentSettings);
} else {
$http.post('GetCompanies')
.then(function (response) {
var response = $.parseJSON(response.data)
currentSettings = response;
def.resolve(currentSettings);
});
}
return def.promise;
}
}]);
myApp.service('docTypeService', ['$http', '$q', function ($http, $q) {
var docSettings = null;
this.getList = function () {
var def = $q.defer()
if (docSettings) {
def.resolve(docSettings);
} else {
$http.post('GetDocTypes')
.then(function (response) {
var response = $.parseJSON(response.data)
docSettings = response;
def.resolve(docSettings);
});
}
return def.promise;
}
}]);
myApp.service('allCurrentSettingsService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getList = function () {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings')
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);
myApp.controller('myController', ['$scope', 'companiesService', 'docTypeService', 'allCurrentSettingsService',
function ($scope, companiesService, docTypeService, allCurrentSettingsService) {
$scope.currentSettings = '';
companiesService.getList().then(function (value) {
$scope.currentSettings = value;
});
$scope.docSettings = '';
docTypeService.getList().then(function (value) {
$scope.docSettings = value;
});
$scope.allSettings = '';
allCurrentSettingsService.getList().then(function (value) {
$scope.allSettings = value;
});
}
]);
And my HTML`
<table>
<tr>
<td>Select a company:</td>
<td>
<div data-ng-controller="myController">
<select ng-model="dropdownvalue" ng-change="GetDocTypes(dropdownvalue)">
<option data-ng-repeat="currentSetting in currentSettings" value={{currentSetting.SCACCode}}>{{currentSetting.SCACCode}}</option>
</select>
</div>
</td>
</tr>
<tr>
<td>Enter customer: </td>
<td><div><input id="Text1" type="text" /></div></td>
</tr>
<tr>
<td>Select document:</td>
<td>
<div ng-controller="myController">
<select>
<option>Select document</option>
<option ng-repeat="docSetting in docSettings" value="{{docSetting.Doc_Type}}">{{docSetting.Doc_Type}}</option>
</select>
</div>
</td>
</tr>
</table>
`
My MVC Controller
`
public JsonResult GetDocTypes(string company)
{
var jsonString = string.Empty;
string query = "SELECT * FROM Companies WHERE CompName = #Company";
try
{
using (SqlConnection conn = new SqlConnection(connStringEbe))
{
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
DataTable dt = new DataTable();
command.Parameters.Add(new SqlParameter("#Company", company));
using (SqlDataReader rdr = command.ExecuteReader())
{
dt.Load(rdr);
}
command.Parameters.Clear();
jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Formatting.None);
return Json(jsonString);
}
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
return Json(jsonString);
}
}
`

angularjs: unable to get data from factory

I am unable to get my json data from factory and show it in table.
When I was using the $scope object, it was working fine but then I saw in official website that they don't recommend using $scope anymore. So I am using this parameter as suggested in demo examples. And now my code is not working anymore.
Please see my code and help me in this regard:
HTML:
<body ng-app="admin">
<div ng-controller="controller1 as ctrl1">
<div class="container">
<div class="row">
<div class="col-sm-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>IP</th>
<th>Time</th>
<th>No. of times</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="iprow in ctrl1.ipLog">
<td>{{iprow.ip}}</td>
<td>{{iprow.time}}</td>
<td>{{iprow.count}}
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="../framework/angular/angular.min.js"></script>
<script src="javascript/app.js"></script>
<script src="javascript/controllers/profileController.js"></script>
</body>
angular app.js
var admin = angular.module('admin', ['myController']);
admin.factory('simpleFactory', function ($http) {
var ipLog = [];
var factory = {};
factory.getIpLog = function () {
// Simple GET request example:
return $http({method: 'GET', url: 'mysql-query.php'}).
then(function successCallback(response) {
ipLog = response.data;
return ipLog;
}, function errorCallback(response) {
console.log(response.data);
return ipLog;
});
};
return factory;
});
angular profileController.js
var myController = angular.module('myController', []);
myController.controller('controller1', ['simpleFactory', function (factory) {
this.ipLog = [];
init();
function init() {
var myDataPromise = factory.getIpLog();
myDataPromise.then(function (result) {
// this is only run after getData() resolves
this.ipLog = result;
});
}
}]);
Your view:
<body ng-app="admin">
<div ng-controller="controller1">
...
<tr ng-repeat="iprow in ipLog">
...
</body>
factory code:
var admin = angular.module('admin', []);
admin.factory('simpleFactory', function ($http) {
var factory = {};
factory.getIpLog = function () {
// Simple GET request example:
return $http({method: 'GET', url: 'mysql-query.php'});
};
return factory;
});
Grab the factor module inside the controller.
Controller:
var myController = angular.module('myController', ['admin']);
myController.controller('controller1', ['simpleFactory', function (factory) {
$scope.ipLog = [];
function init() {
var myDataPromise = factory.getIpLog();
myDataPromise.then(function (result) {
$scope.ipLog = result.data;
});
}
init();
}]);
in app.js
factory.getIpLog = function () {
// Simple GET request example:
return $http({method: 'GET', url: 'mysql-query.php'});
};
in profileController.js
myController.controller('controller1', ['simpleFactory', function (factory) {
this.ipLog = [];
init();
function init() {
var myDataPromise = factory.getIpLog();
myDataPromise.then(function (success) {
this.ipLog = success;
}, function(error){
console.log(error);
});
}
}]);
In your profileController.js, this in this.ipLog=[] refers to myController but when when you are assigning value to this.ipLog=result, this here doesn't refer to myController. SO your this.ipLog is always an empty array.
try this code:
var myController = angular.module('myController', []);
myController.controller('controller1', ['simpleFactory', function (factory) {
var fixedThis=this;
fixedThis.ipLog = [];
init();
function init() {
var myDataPromise = factory.getIpLog();
myDataPromise.then(function (result) {
// this is only run after getData() resolves
fixedThis.ipLog = result;
});
}
}]);
Please try this code and tell if it works.

AngularJS Chart Directive - Data loaded in async service not updating chart

I am having one chart directive created, and I am bootstrpping the app after loading google api. In following code, a simple data table is working fine. But when I load data from server in async manner, chart is not being displayed.
Controller
'use strict';
myNetaInfoApp.controller('allCandidatesController', [
'$scope','allCandidates2009Svc', '$timeout',
function ($scope, allCandidates2009Svc, $timeout) {
$scope.data1 = {};
$scope.data1.dataTable = new google.visualization.DataTable();
$scope.data1.dataTable.addColumn("string", "Party");
$scope.data1.dataTable.addColumn("number", "qty");
$scope.data1.dataTable.title = "ASDF";
$timeout( function (oldval, newval) {
allCandidates2009Svc.GetPartyCriminalCount().then(function(netasParty) {
var i = 0;
for (var key in netasParty) {
$scope.data1.dataTable.addRow([key.toString(), netasParty[key]]);
i++;
if (i > 20) break;
}
});
});
$scope.dataAll = $scope.data1;
//sample data
$scope.data2 = {};
$scope.data2.dataTable = new google.visualization.DataTable();
$scope.data2.dataTable.addColumn("string", "Name");
$scope.data2.dataTable.addColumn("number", "Qty");
$scope.data2.dataTable.addRow(["Test", 1]);
$scope.data2.dataTable.addRow(["Test2", 2]);
$scope.data2.dataTable.addRow(["Test3", 3]);
}
]);
Service
'use strict';
myNetaInfoApp.factory('allCandidates2009Svc', ['$http', '$q',
function ($http, $q) {
var netas;
return {
GetPartyCriminalCount: function () {
var deferred = $q.defer();
$http.get('../../data/AllCandidates2009.json')
.then(function (res) {
netas = res;
if (netas) {
var finalObj = {};
_.each(netas.data, function(neta) {
finalObj[neta.pty] = finalObj[neta.pty] ? finalObj[neta.pty] + 1 : 1;
});
deferred.resolve(finalObj);
}
});
return deferred.promise;
}
};
}]);
Directive
"use strict";
var googleChart = googleChart || angular.module("googleChart", []);
googleChart.directive("googleChart", function () {
return {
restrict: "A",
link: function ($scope, $elem, $attr) {
var dt = $scope[$attr.ngModel].dataTable;
var options = {};
if ($scope[$attr.ngModel].title)
options.title = $scope[$attr.ngModel].title;
var googleChart = new google.visualization[$attr.googleChart]($elem[0]);
$scope.$watch($attr.ngModel, function (oldval, newval) {
googleChart.draw(dt, options);
});
}
};
});
HTML
<div ng-controller="allCandidatesController">
<div class="col-lg-6">
<h2>Parties and Candidates with Criminal Charges</h2>
<div google-chart="PieChart" ng-model="dataAll" class="bigGraph"></div>
<!--<p><a class="btn btn-primary" href="#" role="button">View details ยป</a></p>-->
</div>
<div class="col-lg-6">
<h2>Heading</h2>
<div google-chart="BarChart" ng-model="data2" class="bigGraph"></div>
</div>
</div>
I think you need to wrap your function body in allCandidates2009Svc factory with scope.$apply(). But the return deferred.resolve() will be outside scope.$apply().
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function() {
// since this fn executes async in a future turn of the event loop, we need to wrap
// our code into an $apply call so that the model changes are properly observed.
scope.$apply(function() {
deferred.notify('About to greet ' + name + '.');
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
});
}, 1000);
return deferred.promise;
}
Read the docs here
http://docs.angularjs.org/api/ng.$q

Resources