I have two Models named "Jeans" and "Shirts"
which have two variables "name" and "color"
I want to have a search page in which user can search through database to find shirts and jeans in specific color or name.
This link might be a hint but I just could not figure it out
Similar Problem
I have got something here But it does not work.
I appreciate if you tell me how to fix it.Thanks!
View
<section data-ng-controller="AllsController" data-ng-init="find()">
<div class="page-header">
<h1>Alls</h1>
</div>
<div class="Search">
<h2>Search Section</h2>
<select data-ng-model="search1" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
<select data-ng-model="search2" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
<select data-ng-model="variable1" id="variable1">
<option selected="selected">AnyThing</option>
<option value="color1">Blue</option>
<option value="color2">Red</option>
</select>
<select data-ng-model="variable2" id="variable2">
<option selected="selected">AnyThing</option>
<option value="name1">John</option>
<option value="name2">Bob</option>
</select>
</div>
<br></br><br></br>
<h2>Result Section</h2>
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="all in alls">
<td data-ng-bind="all.name"></td>
<td data-ng-bind="all.color"></td>
</tr>
</tbody>
</table>
</div>
In controller; first I see which properties user has selected and assign it to FindArray
Then I see in which model user want to search.(AnyThing means that user has not selected anything)
Server Side Controller
exports.list = function(req, res) {
if (variable1 === "AnyThing")
{
if (variable2 === "AnyThing")
{
FindArray = {};
}else
{
FindArray = { name = variable2 };
}
}else
{
FindArray = { color = variable1 , name = variable2 };
}
if (req.body.search1 === 'Jeans')
{
if (req.body.search2 === 'Shirts')
{
Jeans.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Shirt.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
var all = shirts.concat(jeans);
res.jsonp(all);
});
});
}else{
Jeans.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
res.jsonp(jeans);
});
}
}else{
Shirt.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
res.jsonp(shirts);
});
}
};
$Resource Service:
angular.module('alls').factory('Alls', ['$resource',
function($resource) {
return $resource('alls/:allId', { allId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
Client Side Controller
angular.module('alls').controller('AllsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Alls', 'Jeans', function($scope, $stateParams, $location, Authentication, Alls, Jeans) {
$scope.find = function() {
$scope.search1 = search1;
$scope.search2 = search2;
$scope.variable1 = variable1;
$scope.variable2 = variable2;
$scope.alls = Alls.query();
};
}]);
Server Side Route
module.exports = function(app) {
var alls = require('../../app/controllers/alls.server.controller');
app.route('/alls').get(alls.list);
};
Preliminary review of this looks to me like your route is expecting a get, but your $resource is running a put. I'm also thinking that all of your scope assignments aren't going to work because you're assigning non existent variables.
Related
I do not understand why ng-options is not populating the dropdown menu. JSON data is being returned from the service. I can console.log the data in the controller. So, why is ng-options not populating the dropdown
<tr class="info">
<td class = "col-xs-3">Maximum page size: </td>
<td class = "col-xs-9" ng-controller = "converseController"> Show conversations per page
<select ng-model = "selectedNumber" ng-options="conversation for conversation in conversations">
<option value = ""> Choose the number of conversations </option>
</select>
<aside id = "pageSize"> Show contacts per page
<select>
<option> 20 </option>
</select>
</aside>
</td>
</tr>
converse.js - Controller
(function() {
'use strict';
var converseController = function (getData, $scope) {
var url = '../../data/conversation.json';
getData.fetchData(url)
.then(function(data){
$scope.coversations = data.conversation;
console.log($scope.coversations);
});
};
angular.module('assignment3App')
.controller ('converseController', ['getData', '$scope', converseController]);
}());
conversation.json
{
"conversation": [
10,
20,
30,
40,
50,
60,
70,
80,
90,
100
]
}
Service - promise.js
(function() {
'use strict';
var getData = function (fetchDataService) {
this.fetchData = function(filePath) {
return fetchDataService.getContent(filePath)
.then(function (returnedData) {
return returnedData.data;
});
};
};
angular.module('assignment3App')
.service ('getData', ['fetchDataService', getData]);
}());
Service - callJson.js
(function() {
'use strict';
var fetchDataService = function($http) {
this.getContent = function(path) {
return $http({
method : 'get',
url : path
});
};
};
angular.module('assignment3App')
.service ('fetchDataService', fetchDataService);
}());
You are assinging the array to the wrong scope variable. $scope.coversations = data.conversation; should be spelt $scope.conversations = data.conversation;.
So I have a form inside an ng-dialog plugin for angular js. The contents of the ng-dialog is loaded from external html file. The problem is that when I try to save the data it is undefined. I suspect that I am missing updating the ng-model that I use, but it is not clear how to do it. I have looked to some similar examples, but it still does not work.I want to collect the data when the button inside the form is pressed, not when the dialog is closed, but when closed will do as well. Here is my code:
angular.app.js
myApp.controller('RequestController', function ($scope, $http, $location, $window, subtitleRequestService, $sce, subtitlesApiServiceUrl, helperService, ngDialog) {
$scope.string_identifier = helperService.getParameterByName("v");
$scope.availableSubtitles = null;
$scope.request = {
status: "pending",
status_reason: "",
status_reason_f: ""
};
var getAvailableSubtitles = function()
{
subtitleRequestService.getAvailableSubtitlesForRequest().then(
function (res) {
var subs = res.data.message;
$scope.availableSubtitles = subs;
},
function () {
alert('Error');
}
);
};
$scope.saveStatus = function()
{
var sts = ($scope.request.status_option === "accepted" ? $scope.request.status_reason : $scope.request.status_reason_f);
$http.post(subtitlesApiServiceUrl + "changeRequestStatus/request_id/" + $scope.string_identifier + "/status/" + $scope.request.status + "/status_reason/" + sts)
.success(function (data, status, headers, config) {
alert(data.message);
}).error(function (data, status, headers, config) {
alert(data);
});
};
$scope.changeStatus = function()
{
getAvailableSubtitles();
var dialogInstance = ngDialog.open({
//appendTo: window.parent.document.getElementsByTagName('body'),
template: "/templates/change-request-status.html",
scope: $scope,
controller: 'RequestController',
className: 'ngdialog-theme-default'
});
};
});
externalTeamplate.html
<div class="ngdialog-message" ng-controller="RequestController">
<h3>Schimbă status</h3>
<div class="form">
<form class="form" name="$scope.request">
<div class="row">
<label for="status_options">Status</label>
<select name="status_options" id="status_options" ng-model="request.status_option">
<option value="pending" selected="selected">În procesare</option>
<option value="accepted">accepted</option>
<option value="rejected">rejected</option>
<option value="deleted">deleted</option>
<option value="in_translation">in_translation</select>
</select>
</div>
<div class="row" ng-show="request.status_option !== 'accepted'">
<label for="status_reason">Reason:</label>
<input type="text" id="status_reason" size="35" maxlength="144" ng-model="request.status_reason" />
</div>
<div class="row" ng-show="request.status_option=='accepted'">
<label for="status_reason_f">Please select:</label>
<select id="status_reason_f" ng-repeat="(key, value) in availableSubtitles" ng-model="request.status_reason_f">
<option value="{{key}}">{{value}}</option>
</select>
</div>
</form>
</div>
</div>
<div class="ngdialog-buttons">
<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="saveStatus()">Salvează</button>
</div>
What am I missing? Thanks!
I'm currently learning new MVC 6 and stucked completely with simple action - table data update on item selection change.The desired behaviour is to load questions that belong selected question block
I have angularJS factory:
(function () {
'use strict';
angular
.module('questionBlockApp')
.factory('questionBlockService', questionBlockService);
var questionBlockService = angular.module('questionBlockService', ['ngResource']);
questionBlockService.factory('Blocks', ['$resource',
function ($resource) {
return $resource('/api/blocks/', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
questionBlockService.factory('Questions', ['$resource',
function ($resource) {
return $resource('/api/blocks/:blockId', {blockId : '#blockId'}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
Controller, which has refresh func (loadQuestions) built inside selection change function:
(function () {
'use strict';
angular
.module('questionBlockApp')
.controller('questionBlockController', questionBlockController);
//.controller('questionController', questionController);
questionBlockController.$inject = ['$scope', 'Blocks', 'Questions'];
//questionController.$inject = ['$scope', 'Questions'];
function questionBlockController($scope, Blocks, Questions) {
$scope.selectedBlock = 2;
if ($scope.Blocks == undefined | $scope.Blocks == null) {
$scope.Blocks = Blocks.query();
}
$scope.setSelected = function (blockId) {
$scope.selectedBlock = blockId;
$scope.loadQuestions();
}
$scope.loadQuestions = function () {
$scope.data = Questions.query({ blockId: $scope.selectedBlock });
$scope.data.$promise.then(function (data) {
$scope.Questions = data;
});
};
$scope.loadQuestions();
}
})();
And views:
View from which setSelected is called:
<table class="table table-striped table-condensed" ng-cloak ng-controller="questionBlockController">
<thead>
...
</thead>
<tbody>
<tr ng-repeat="block in Blocks" ng-click="setSelected(block.Id)" ng-class="{'selected': block.Id == selectedBlock}">
<td>{{block.Id}}</td>
<td>{{block.Name}}</td>
<td>{{block.Created}}</td>
</tr>
</tbody>
</table>
<table id="test" ng-controller="questionBlockController">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr ng-repeat="question in Questions">
<td>{{question.Id}}</td>
<td>{{question.Text}}</td>
<td>{{question.TimeLimit}}</td>
<td>{{question.Updated}}</td>
</tr>
</tbody>
</table>
When I click on different items in QuestionBlock table, $scope.Questions is updated properly, but the table does not reflect changes, as if no binding exists.
Okay, I am just a bit damaged.
There are two questionBlockController controllers defined, leading to intialization of different scopes => two $scope.Questions objects existence => refresh occured in Blocks scope, which was undesired behaviour.
I am using AngularJS and to show products in a table to my users. Here the user can filter the table using categories or other key words. But the user has to be able to edit the product table, like editing product names or prices and these data has to be altered also in my database of course. Now I am using xeditable which works great and I am able to get the productID which I have to change and the function to change the data gets called but that's it. Here can you see my code:
AngularJS
categorieFilter = angular.module("categorieFilter", ["xeditable"])
categorieFilter.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.postname = function ($prodid){
$http.get('api/editproduct/id/$scope.product.name')
.success(function(results){
})
.error(function(data, status){
console.error("Category add error: ", status, data);
});
};
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
var prods = [];
$http.get('api/products').success(function (data) {
for(var i = 0;i<data.length;i++)
{
prods[i] = {id: data[i][0], name: data[i][1], category: data[i][3], price: data[i][2]};
}
deferred.resolve(prods);
})
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
HTML
<div ng-app="categorieFilter" ng-cloak="" ng-controller="catFilter">
<div class="input-group">
<input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>
<div class="input-group-btn">
<button class="btn btn-sm btn-default">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<div>
<input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">
</div>
<table class="table table-hover">
<tr style="background-color:#ddd;">
<th colspan="4" style="text-align:left; font-size:16px;"> Category </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Product </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Price </th>
</tr>
<tr ng-repeat="product in products | filter:search | orderBy: 'category'">
<td colspan="4">{{product.category}}</td>
<td colspan="4" onaftersave="postname(product.id)" editable-text="product.name">{{product.name}}</td>
<td colspan="4" editable-text="product.price">{{product.price}}</td>
</tr>
</table>
I(m getting error:
ReferenceError: $http is not defined
So what am I doing wrong here? How can I update the required data in my database after changing it in my table using angular and xeditable..?
I updated my controller and function like this and now it works fine:
categorieFilter.controller("catFilter", ["$scope", "$http", "store", function($scope, $http, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.postname = function ($prodid, $prodname){
alert($prodname);
$http.get('api/editproduct/'+$prodid+'/'+$prodname)
.success(function(results){
})
.error(function(data, status){
console.error("Category add error: ", status, data);
});
};
Problem Question -
I have a two drop down in my view. And second drop down rely on the first one. But somehow second one does not get updated
// my firstdrop down
<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
// my second drop down
<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData">
<option value="">Please select cost</option>
</select>
// my controller
(function() {
var myController = function($scope,Service){
$scope.customerDetailData;
Service.cust()
.success(function(data){
console.log(data)
$scope.customerDetailData = data;
})
.error(function(status,error){
})
$scope.customerCostData;
$scope.updateCost=function(customer){
Service.cost(customer.id)
.success(function(cost){
$scope.customerCostData= cost
})
.error(function(status,data){
console.log(status);
console.log(data);
})
}
};
myController .$inject = ['$scope','Service'];
angular.module('app').controller('myController ',myController );
}());
Is anything i am missing ? the data is coming through fine in the console. Please guide me
There are 2 things to do here:
The first and main issue is that you are attaching ng-controller to each select individually. This means it is actually creating 2 separate controllers, one for each select, and so they are given different scopes. You need to apply the ng-controller attribute to a parent element, such as the form.
The second issue is that angular will not automatically update an element just because the scope variable is used in ng-options. You therefore need to give it a ng-model so that Angular watches it correctly.
Here is an example of the code with two separate controller instances. Note the 2 alerts:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<form ng-app="myApp">
<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
<option value="">Please select cost</option>
</select>
</form>
<script type="text/javascript">
(function () {
var myApp = angular.module('myApp', []);
var myController = function ($scope) {
alert('myController created');
$scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];
$scope.updateCost = function (customer) {
$scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
}
};
myController.$inject = ['$scope'];
myApp.controller('myController', myController);
}());
</script>
Here it is with the single ng-controller applied to the form and ng-model="customerCostData" on the second select, so it now works:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myController">
<select
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
<select
ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
<option value="">Please select cost</option>
</select>
</form>
<script type="text/javascript">
(function () {
var myApp = angular.module('myApp', []);
var myController = function ($scope) {
alert('myController created');
$scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];
$scope.updateCost = function (customer) {
// would be an ajax call
$scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
}
};
myController.$inject = ['$scope'];
myApp.controller('myController', myController);
}());
</script>
is the cost data the result of an Ajax request? if so, you may need to force a force a $digest cycle to let the UI know the model has been changed. You can achieve this by wrapping the assignment of cost in a $timeout, or $apply.
$timeout(function () {
$scope.customerCostData = cost;
});
or
$scope.$apply(function () {
$scope.customerCostData = cost;
});