I suspect what I'm trying to do is very simple, I'm new to Angular so some obvious practices sort of go over my head. I'm having trouble accessing the show view (sorry, I'm coming to angular from Rails, so I still think in those terms a little bit) for my Acts resource. The view renders fine, but it isn't displaying the data I would like. I suspect the template isn't receiving the $scope.act variable I'm defining in the controller. When I use console.log in the controller, I can see that the variable contains all the data I want to use. I assume I have to do something to pass the variable as a parameter to the template, but I'm not sure how I'd do that.
Here's my code:
app.js
$(document).on('page:load', function() {
return $('[ng-app]').each(function() {
var module;
module = $(this).attr('ng-app');
return angular.bootstrap(this, [module]);
});
});
var snowball_effect = angular.module('snowball_effect', [
'templates',
'ngRoute',
'ngResource',
'controllers'
]);
snowball_effect.config([
'$routeProvider', function($routeProvider) {
return $routeProvider
.when('/', {
templateUrl: "static_pages/templates/index.html",
controller: 'StaticPagesController'
})
.when('/acts/index', {
templateUrl: "acts/templates/index.html",
controller: 'ActsController'
})
.when('/acts/:id', {
templateUrl: "acts/templates/show.html",
controller: 'ActsController'
});
}
]);
var controllers = angular.module('controllers', []);
ActsController.js
controllers = angular.module('controllers');
controllers.controller('ActsController', [
'$scope',
'$routeParams',
'$location',
'$resource',
function($scope,$routeParams,$location,$resource) {
var Act = $resource('/acts/:actId', {
actId: "#id",
format: 'json'
}, {
'create': {
method: 'POST'
}
});
$scope.acts = Act.query();
$scope.addAct = function() {
act = Act.save($scope.newAct, function() {
$scope.acts.push(act);
$scope.newAct = '';
});
}
$scope.deleteAct = function(act) {
Act.delete(act);
$scope.acts.splice($scope.acts.indexOf(act), 1);
}
$scope.linkToShowAct = function(act) {
$scope.act = act;
console.log($scope.act);
$location.path('acts/' + act.id);
}
}]);
show.html
<div class="acts-show">
<div class="container" ng-controller="ActsController">
<div class="body">
<h1>
{{act.name}}
</h1>
<p class="act-show-description">
{{act.description}}
</p>
<p class="act-show-inspires">
<strong>Inspires:</strong>
{{act.inspires}}
</p>
Edit
Back
</div>
</div>
</div>
index.html
<div class="actions_body">
<div class="container">
<h2>Listing Actions</h2>
<div ng-controller="ActsController" class="body">
<table class="row">
<thead>
<tr>
<th class="col-md-2 col-md-offset-1 active">
<label>Name</label>
</th>
<th class="col-md-4">Description</th>
<th class="col-md-2">Inspires</th>
<th colspan="2" class="col-md-2">Modify</th>
</tr>
</thead>
<tbody ng-repeat="act in acts">
<td class="col-md-offset-1 col-md-2">{{act.name}}</td>
<td class="col-md-4">{{act.description}}</td>
<td class="col-md-2">{{act.inspires}}</td>
<td>Edit</td>
<td><button ng-click="deleteAct(act)">Delete</a></button>
</tbody>
</table>
<br>
<button ng-click="newActShow=true">New Action</button>
<button ng-click="newActShow=false">Hide</button>
<div ng-show="newActShow" id="newAct">
<div class="row">
<form class="form-inline" ng-submit="addAct()">
<div class="col-md-3 form-group">
<label for="newActname">Name</label>
<input type="text" ng-model="newAct.name" id="newActname" placeholder="Name" class="form-control col-md-2">
</div>
<div class="col-md-3 form-group">
<label for="newActdescription">Description</label>
<input type="textarea" ng-model="newAct.description" id="newActdescription" placeholder="Description" class="form-control col-md-2">
</div>
<div class="col-md-3 form-group">
<label for="newActinspires">Inspires</label>
<input type="number" ng-model="newAct.inspires" id="newActinspires" placeholder="Inspires" class="form-control col-md-2">
</div>
<div class="col-md-3 form-group">
<input type="submit" value="+" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
try $locationChangeStart in order to make sure your value is set to the scope variable before the state actually changes and the route happens, even if you put the $location.path('acts/' + act.id); before setting the variable, there is no guarantee that the value will be set before the state change (the actual routing).
I would prefer (a more safe value setting method) using a promise for example ..
Related
This is for an academic assignment. It is my first time using Angularjs and I am trying to display data onto the webpage. On the Chrome console I am getting a http response code 200 which means I am successfully getting the data but it just does not seem to be displaying.
groups.html :
<html>
<head>
<script src = "groups.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="groupsCtrl">
<div class="group-jumbotron">
<h1 class="display-4">Champion's League Groups</h1>
<p class="lead">The 2018–19 UEFA Champions League group stage began on 18 September and is scheduled to end on 12 December 2018. <br/>
A total of 32 teams compete in the group stage to decide the 16 places in the knockout phase of the 2018–19 UEFA Champions League.</p>
<hr class="my-1">
<p>Information about each group can be seen below</p>
</div>
<div class="addGroup-Title">
<h4 class="display-6">Groups:</h4>
<table>
<thead>
<tr>
<th>Group Letter</th>
<th>Number of Teams</th>
<th>Matches Played</th>
<th>Top Goalscorer</th>
<th>Top Assists</th>
<th>Most Cards</th>
<th>Total Points</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="group in leagueGroup">
<td>{{group.groupLetter}}</td>
<td>{{group.numberOfTeams}}</td>
<td>{{group.totalMatchesPlayed}}</td>
<td>{{group.topGoalscorer}}</td>
<td>{{group.topAssists}}</td>
<td>{{group.mostCards}}</td>
<td>{{group.totalPoints}}</td>
</tr>
</tbody>
</table>
</div>
<div class="addGroup-Title">
<h4 class="display-6">Add a New Group:</h4>
<form ng-show="showForm" ng-submit="submitNewGroupForm()" style="margin-left: 10px;margin-right: 10px" ng-model="newGroup">
<div class="form-row">
<div class="form-group col-md-3">
<label for="AddGroupLetter">Group Letter:</label>
<input type="text" ng-model="newGroup.groupLetter"class="form-control" id="AddGroupLetter" min="1" max="2" required>
</div>
<div class="form-group col-md-3">
<label for="AddnumTeams">Number of Teams:</label>
<input type="number" class="form-control" id="AddnumTeams" ng-model="newGroup.numberOfTeams" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="AddTotalMatches">Total Matches Played:</label>
<input type="number" class="form-control" id="AddTotalMatches" ng-model="newGroup.totalMatchesPlayed" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="AddTotalPoints">Total Points:</label>
<input type="number" class="form-control" id="AddTotalPoints" ng-model="newGroup.totalPoints" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="AddTopGoalscorer">Top Goalscorer:</label>
<input type="text" class="form-control" id="AddTopGoalscorer" ng-model="newGroup.topGoalscorer" required>
</div>
<div class="form-group col-md-3">
<label for="AddTopAssists">Top Assists:</label>
<input type="text" class="form-control" id="AddTopAssists" ng-model="newGroup.topAssists" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="AddMostCards">Most Cards</label>
<input type="text" class="form-control" id="AddMostCards" ng-model="newGroup.mostCards" required>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg">Create A Group</button>
</form>
</div>
<div class="addGroup-Title">
<h4 class="display-6">Delete a Group:</h4>
<div class="form-row">
<div class="form-group col-md-6">
<label for="DeleteGroup">ID of Group</label>
<input type="text" class="form-control" id="DeleteGroup" ng-model="groupData.groupId" required>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg">Delete A Group</button>
</div>
</div>
</div>
</body>
</html>
groups.js :
'use strict';
angular.module('myApp.groups', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/groups', {
templateUrl: 'groups/groups.html',
controller: 'groupsCtrl'
});
}])
.controller('groupsCtrl', function ($scope, $http) {
$scope.leagueGroup = [];
$http.get('http://localhost:5000/api/v1/groups')
.then(function (response) {
$scope.leagueGroup = response.data;
});
$scope.submitNewGroupForm = function () {
$scope.newGroup =
{
groupId: getgroupId(),
groupLetter: $scope.newGroup.groupLetter,
numberOfTeams: $scope.newGroup.numberOfTeams,
totalMatchesPlayed: $scope.newGroup.totalMatchesPlayed,
topGoalscorer: $scope.newGroup.topGoalscorer,
topAssists: $scope.newGroup.topAssists,
mostCards: $scope.newGroup.mostCards,
totalPoints: $scope.newGroup.totalPoints
};
$http.post('http://localhost:5000/api/v1/groups', $scope.newGroup)
.then(function (response) {
$scope.response = response.data;
alert('Created new Group: ' + $scope.response.stadiumName);
});
};
$http.delete('http://localhost:5000/api/v1/groups/'+ $scope.groupData.groupId)
.then(function (response) {
$scope.response = response.data;
});
});
function getgroupId() {
return Math.floor((Math.random() * 9999) + 10);
}
Data example:
groupId: 1
groupLetter: "A"
mostCards: "Marcos Rojo"
numberOfTeams: 4
topAssists: "Kevin De Bruyne"
topGoalscorer: "Cristiano Ronaldo"
totalMatchesPlayed: 6
totalPoints: 48
response(chrome dev):
[
{
"groupId":1,
"groupLetter":"A",
"mostCards":"Marcos Rojo",
"numberOfTeams":4,
"topAssists":"Kevin De Bruyne",
"topGoalscorer":"Cristiano Ronaldo",
"totalMatchesPlayed":6,
"totalPoints":48
},
{
"groupId":2,
"groupLetter":"B",
"mostCards":"Ander Herrera",
"numberOfTeams":4,
"topAssists":"Luka Modric",
"topGoalscorer":"Sergio Aguero",
"totalMatchesPlayed":6,
"totalPoints":36
},
{
"groupId":3,
"groupLetter":"C",
"mostCards":"Sergio Ramos",
"numberOfTeams":4,
"topAssists":"Xavi",
"topGoalscorer":"Lionel Messi",
"totalMatchesPlayed":6,
"totalPoints":50
},
{
"groupId":4,
"groupLetter":"D",
"mostCards":"Virgil Van Dijk",
"numberOfTeams":4,
"topAssists":"Neymar",
"topGoalscorer":"Kylian MBappe",
"totalMatchesPlayed":6,
"totalPoints":32
}
]
After a lot of head banging it turns out in my groups.js i am calling all of my methods such as http.get in the same functions. They need to be called on seperate functions so that they all dont run when the screen loads. Once i re-organised into seperate functions the data displayed.
Thanks for the help everyone
Your module name seems to be wrong. You've named it myApp.groups but it should just be myApp.
angular.module('myApp.groups', ['ngRoute'])
Should be:
angular.module('myApp', ['ngRoute'])
Are you getting any errors in the console?
const data = [{
"groupId": 1,
"groupLetter": "A",
"mostCards": "Marcos Rojo",
"numberOfTeams": 4,
"topAssists": "Kevin De Bruyne",
"topGoalscorer": "Cristiano Ronaldo",
"totalMatchesPlayed": 6,
"totalPoints": 48
},
{
"groupId": 2,
"groupLetter": "B",
"mostCards": "Ander Herrera",
"numberOfTeams": 4,
"topAssists": "Luka Modric",
"topGoalscorer": "Sergio Aguero",
"totalMatchesPlayed": 6,
"totalPoints": 36
},
{
"groupId": 3,
"groupLetter": "C",
"mostCards": "Sergio Ramos",
"numberOfTeams": 4,
"topAssists": "Xavi",
"topGoalscorer": "Lionel Messi",
"totalMatchesPlayed": 6,
"totalPoints": 50
},
{
"groupId": 4,
"groupLetter": "D",
"mostCards": "Virgil Van Dijk",
"numberOfTeams": 4,
"topAssists": "Neymar",
"topGoalscorer": "Kylian MBappe",
"totalMatchesPlayed": 6,
"totalPoints": 32
}
];
const app = angular.module('myApp',[]);
app
.controller('groupsCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
$timeout(1000)
.then(function() {
$scope.leagueGroup = data;
});
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<html>
<body>
<div ng-app="myApp">
<div ng-controller="groupsCtrl">
<div class="addGroup-Title">
<h4 class="display-6">Groups:</h4>
<table>
<thead>
<tr>
<th>Group Letter</th>
<th>Number of Teams</th>
<th>Matches Played</th>
<th>Top Goalscorer</th>
<th>Top Assists</th>
<th>Most Cards</th>
<th>Total Points</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="group in leagueGroup">
<td>{{group.groupLetter}}</td>
<td>{{group.numberOfTeams}}</td>
<td>{{group.totalMatchesPlayed}}</td>
<td>{{group.topGoalscorer}}</td>
<td>{{group.topAssists}}</td>
<td>{{group.mostCards}}</td>
<td>{{group.totalPoints}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Have you done a console.log with the response object to ensure it's what you expect it to be?
Do it here:
.then(function (response) {
console.log(response);
$scope.leagueGroup = response.data;
$scope.$apply();
});
Have you tried doing a $scope.$apply() after you assign the data?
Another option to confirm that your data is correct is to simply put a <pre> tag in your template to confirm the data is bound, like this:
<pre>{{leagueGroup}}</pre>
ng-app is added in the html tag. I have added just a portion of html code.
I am trying to use the CreatePortfolioController but it seems to be undefined. I checked for typo errors too, but there seems to be none. I have no idea why it is not working. Can you please help me debug?
App.js
var app = angular.module("UiApp", ["ServiceApp"]);
app.service('sharedProperties', function () {
var idValue = 'test string value';
return {
getId: function () {
return idValue;
},
setId: function (value) {
idValue = value;
}
}
});
app.controller("PortFolioController", function ($scope, GetPortfolios, sharedProperties) {
$scope.Portfolios = GetPortfolios.query({ pmid: 2 });
console.log($scope.Portfolios);
$scope.addOrder = function (id) {
sharedProperties.setId(id)
};
});
app.controller("CreatePortfolioController", function ($scope, CreatePortfolio) {
$scope.create = function (data) {
CreatePortfolio.save(data);
};
});
app.controller("OrderController", function ($scope, GetOrders, sharedProperties) {
$scope.$watch(function () {
return sharedProperties.getId()
}, function (newValue, oldValue) {
if (newValue != oldValue) {
$scope.item = newValue;
$scope.Orders = GetOrders.query({ id: item });
}
});
});
Service.js
var app = angular.module("ServiceApp", ["ngResource"]);
app.factory('GetPortfolios', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/");
});
app.factory('GetOrders', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/");
});
app.factory('CreatePortfolio', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/CreatePortfolio");
});
Html
<div class="panel-body">
<div class="form" ng-controller="CreatePortfolioController">
<form class="cmxform form-horizontal " id="signupForm" method="get" ng-submit="create(data)" action="">
<div class="form-group ">
<label for="portfolioname" class="control-label col-lg-3">Portfolio Name</label>
<div class="col-lg-6">
<input class= "form-control" ng-model="data.portfolioName" name="portfolioname" type="text" required />
</div>
</div>
<div class="form-group ">
<label for="portfoliotype" class="control-label col-lg-3">Portfolio Type</label>
<div class="col-lg-6">
<input class= "form-control" ng-model="data.type" name="portfoliotype" type="text" required />
</div>
</div>
<div class="form-group ">
<label for="portfoliodesc" class= "control-label col-lg-3">Portfolio Description</label>
<div class="col-lg-6">
<textarea class="form-control " ng-model="data.description" name="portfoliodesc" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-6">
<button class="btn btn-primary" type="submit">Save <i class="fa fa-check"></i></button><!--Write Save code-->
<button class="btn btn-primary" type="reset">Cancel <i class="fa fa-times"></i></button><!--Write clear text box code-->
</div>
</div>
</form>
</div>
</div>
Sequence of imported files
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-resource.js"></script>
<script src="~/AngularScripts/PM/App.js"></script>
<script src="~/AngularScripts/PM/Service.js"></script>
Please check all these conditions:
Your ng-app is included before the ng-controller in HTML page or
together in the same tag.
Check the name of controller as it is case sensitive.
Make sure you have loaded the JS files properly inside the HTML page. The JS file for AngularJS library, then your app files that
contains, sequentially- JS file with ng-app set, js files that
define services (if any), js files that define factories (if any) ,
js files that define your controllers. Be sure you don't miss to
include any js files and are in proper sequence.
As i do not see controller file included in the <script>, in the snippet you have added.
I have a form, when I submit it, it pushes some object to my array. Beneath that form I have a table that shows all items in that array. I want my table to update automatically (without refreshing the page) when new item pushed.
Submit button:
<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
In my controller:
$scope.updateTable = function() {
setTimeout(function () {
$scope.$apply();
$scope.$digest();
}, 0);
};
However, it does not work.
I tried different approaches like $watch service, but i`ve got the same result.
Table
<div class="row paytable">
<div class="col-xs-10 col-xs-offset-1">
{{payments.length}}
<table class="table table-hover ">
<tr>
<td>Id</td>
<td>Amount</td>
<td>Cause</td>
</tr>
<tr ng-repeat="item in payments">
<td>{{item.id}}</td>
<td>{{item.amount}}</td>
<td>{{item.cause}}</td>
</tr>
</table>
</div>
</div>
Controller
app.controller('mainController', [ 'user', '$rootScope', '$scope', 'payment', '$timeout', function(user, $rootScope, $scope, payment, $timeout) {
user.getUsers();
user.newUser();
$rootScope.currentUser = user.currentUser();
$scope.payments = payment.getPayments();
$scope.newPayment = payment.newPayment;
$scope.updateTable = function() {
setTimeout(function () {
console.log('apply ------------');
$scope.$apply();
$scope.$digest();
}, 0);
};
$scope.showPayMessage = function() {
console.log('im here');
$scope.showSM = true;
$timeout(function() {
$scope.showSM = false;
}, 2000);
};
}]);
payment - my service for array manipulation.
Form
<div class="newpay row" >
<div class=" col-xs-10 col-xs-offset-1">
<h1>Hello, {{currentUser.name}}</h1>
<h4 ng-show="showSM" class="bg-success">Payment confirmed</h4>
<form name="inputform" ng-submit="newPayment(amount, cause); showPayMessage();">
<div class="form-group">
<label for="exampleInputEmail1">Amount</label>
<input type="number" name="amount" ng-model="amount" class="form-control" id="exampleInputEmail1" placeholder="Amount" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Cause</label>
<input type="text" name="cause" ng-model="cause" class="form-control" id="exampleInputPassword1" placeholder="Cause" required>
</div>
<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
</form>
</div>
</div>
payments: {{payments.length}}
<payments-table payments="payments"></payments-table>
To display that table I created directive.
$scope.$apply and $scope.$digest are better suited for working with 3rd party libraries or testing. In your case Angular is well aware to your changes. The thing is, your payments array, that resides in a service should be queried again after submitting a new item (unless you have a direct reference to the array, then no query should be made).
Like this:
View
<form name="inputform" ng-submit="onSubmit()">
Controller
$scope.onSubmit = function() {
newPayment($scope.newItemAmount, $scope.newItemCause); // Assuming they are properties in the controller
showPayMessage();
$scope.payments = payment.getPayments(); // getting the updated array
}
I am new to angular. I have the post list view and post edit view. my list.html. I want to edit the post on clicking the edit button but I am not having a clue on how to get the edit data. My current code looks like
list.html
<table class="table table-striped table-bordered table-hover table-full-width" id="sample_1">
<thead>
<th>Title</th>
<th>Description</th>
<th>Author</th>
<th>Action</th>
</thead>
<tbody>
<tr ng-repeat="post in blog | orderBy:'created_at':true">
<td>{{post.title}}</td>
<td>{{post.description}}</td>
<td>{{post.author}}</td>
<td>
Edit
Delete
</td>
</tr>
</tbody>
</table>
So, on clicking the button, I am navigating to my edit.html which looks like
<form role="form" class="form-horizontal" ng-submit="editPost()">
<div class="form-group">
<label class="col-sm-2 control-label" for="form-field-1">
Title
</label>
<div class="col-sm-9">
<input type="text" placeholder="Post title" id="form-field-1" class="form-control" ng-model="blog.title" value="{{blog.title}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="form-field-2">
Description
</label>
<div class="col-sm-9">
<textarea placeholder="description" rows="5" id="form-field-2" class="form-control" ng-model="blog.description"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="form-field-1">
Author
</label>
<div class="col-sm-9">
<input type="text" placeholder="Author" id="form-field-1" class="form-control" ng-model="blog.author">
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-2">
<button type="submit" class="btn btn-primary btn-sm">Update</button>
</div>
</div>
</form>
now I have make restful api using nodejs which I have tested using postman and its working fine. My api url are like
localhost:3000/api/posts/id
What I want to achieve now is, I want to get the data from the db on clicking the edit button.
my current js declaration
var meanApp = angular.module('meanApp', ['ui.router', 'ngMessages', 'ngResource']);
meanApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('common', {
abstract: true,
views: {
'': {
templateUrl: 'shared/common.html'
},
'header#common': {
templateUrl: 'shared/header.html'
},
'sidebar#common': {
templateUrl: 'shared/sidebar.html'
},
'script#common': {
templateUrl: 'shared/script-init.html'
},
},
})
.state('blogEdit', {
url: '/blog/edit/{id}',
parent: 'common',
views: {
'': {
templateUrl: 'components/blog/edit.html'
},
},
controller: 'postEditController'
})
});
meanApp.controller('postEditController', function(postService, $stateParams, $scope, $http, $location) {
//code to get the data from db using the id of the post
});
Any help will be appreciated.
If your trying to achieve the data from Db using nodejs.I gave my working example nodejs code (DB connectivity),
var pool = require('../config/database');
module.exports.findCampaign = function(req, res) {
//You created properties file and access or using direct query like this
//var findCampaign = select * from campaigns where campaign_sno = ?
// Accessing properties file
var findCampaign = campaignSql.get('main.findCampaign');
pool.query(findCampaign, function(err, rows) {
if (err)
throw err;
// You follow your coding standard here i did example or reference purpose i wrote like this
console.log('Data received from Db:\n');
console.log(rows);
});
};
in your config file where you are routing with ui.router....in the edit blog state:
.state('blogEdit', {
url: '/blog/edit/:id',
parent: 'common',
views: {
'': {
templateUrl: 'components/blog/edit.html'
},
},
controller: 'postEditController'
})
this :id will be treated as url parameters. now in the controller:
meanApp.controller('postEditController', function(postService, $stateParams, $scope, $http, $location) {
postService.getPostById(parseInt($stateParams.id, 10));
});
here, if your id contains character..... you may not have to parse. Now, query your Db in the service..... since you now have the parameter.....
$http({
url: 'your/path/to/server',
method: "GET",
params: {user_id: idFromServiceArgument}
});
I have a modal form that has several inputs text form control. How do I pass the data to post to the database so that ng-grid gets updated?
do I call my ajax create function within the $scope.open controller section? or resolve?
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
};
}]);
the create function
$scope.createMedicalServices = function(){
var providerMedicalServiceAttributes = {};
providerMedicalServiceAttributes.cash_price = $scope.cash_price
providerMedicalServiceAttributes.average_price = $scope.average_price
providerMedicalServiceAttributes.service = $scope.service
var medicalServicesAttributes = {};
medicalServicesAttributes.description = $scope.description
medicalServicesAttributes.service = $scope.service
var newMedicalService = ProviderMedicalService.create(providerMedicalServiceAttributes);
$scope.provider_medical_services.push(newMedicalService);
ProviderMedicalService.update(providerMedicalServiceAttributes, '/providers/services');
};
create function from factory (factory does delete, querying and create)
ProviderMedicalService.prototype.create = function(attr){
return this.service.save(attr);
}
the html for the modal form
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="header-modal">
<h3>Add Service</h3>
</div>
<div class="modal-body">
<form name="myForm" novalidate ng-submit="submit()">
<div class="row well-text-padding">
<div class="col-md-3 modal-form-tag">CPT Code</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-modal" ng-model="CPT_code" placeholder="CPT Code">
</div>
</div>
<label class="checkbox modal-check-box">
<input type="checkbox" ng-model="No_CPT_code">Service does not have a associated CPT Code
</label>
<div class="row well-text-padding">
<div class="col-md-3 modal-form-tag">Description</div>
<div class="col-md-6">
<textarea class="form-control form-control-modal" rows="3" ng-model="Description" placeholder="Add a Description"></textarea>
</div>
</div>
<div class="row well-text-padding">
<div class="col-md-3 modal-form-tag">Average Cost</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-modal" ng-model="Average_cost" placeholder="$">
</div>
</div>
<div class="row well-text-padding">
<div class="col-md-3 modal-form-tag">Offered Price</div>
<div class="col-md-6">
<input type="text" class="form-control form-control-modal" ng-model="Offered_price" placeholder="$">
</div>
</div>
<div class="btn-row2 modal-button-row">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" type="submit">Add Service</button>
</div>
</script>
You can make the POST request to server when clicked Add Service, or you can pass your data from modal to your main controller through $scope.$close().
Example as below:
In modal controller
var data = {
CPT_code: $scope.CPT_code,
No_CPT_code: $scope.No_CPT_code,
Description: $scope.Description,
Average_cost: $scope.Average_cost,
Offered_price: $scope.Offered_price
};
$scope.$close(data); // pass the data through modal close event
Then in your main controller by using the promise to get the data
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
}).result.then(function (response) {
var data = response; // here is your data from your modal
});
};
Hope this helps.