Using Breeze With Web Api And Angular js - javascript

i want to select item from drop down list and then i will see selected customer data in input
then iwant to edit inputs and then save them in database by breez js and web api
I have Web Api Controller like This :
[BreezeController]
public class ZzaController : ApiController
{
readonly EFContextProvider<ZzaDbContext> _contextProvider =
new EFContextProvider<ZzaDbContext>();
// ~/breeze/Zza/Metadata
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
// ~/breeze/Zza/Customers
[HttpGet]
public IQueryable<Customer> Customers()
{
var customers = _contextProvider.Context.Customers;
return customers;
}
// ~/breeze/Zza/SaveChanges
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
}
Angular Service Like This :
var services = function (http) {
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
this.getBybreeze = function (successed) {
var dataService = new breeze.DataService({
serviceName: 'breeze/Zza',
hasServerMetadata: false
});
var manager = new breeze.EntityManager(
{
dataService: dataService
});
var entityQuery = breeze.EntityQuery;
return entityQuery.from('Customers').using(manager).execute().then(successed).catch();
}
this.saveByBreeze =function () {
var dataService = new breeze.DataService({
serviceName: 'breeze/Zza',
hasServerMetadata: false
});
var manager = new breeze.EntityManager(
{
dataService: dataService
});
manager.saveChanges().fail(function (error) { alert("Failed save to server: " + error.message); });
}
}
services.$inject = ["$http"];
app.service("TestService", services);
And Angular Controler Like This :
var controller = function (scope, testService, ngTableParams, filter, upload, notification) {
var self = this;
self.title = "Test";
self.customers = [];
self.selected = "";
self.selectedFirstName="";
self.selectedLastName="";
testService.getBybreeze(function (data) {
self.customers = data.results;
});
self.selectedCustomer = function () {
angular.forEach(self.customers, function (item) {
if (item.Id === self.selected) {
self.selectedFirstName = item.FirstName;
self.selectedLastName = item.LastName;
}
});
}
self.save = function () {
testService.saveByBreeze();
}
}
controller.$inject = ["$scope", "TestService", "NgTableParams", "$filter", "Upload", "Notification"];
app.controller("TestController", controller)
View :
<div class="col-md-12" style="margin-top:20px">
<div class="col-md-2 " style="margin-top: 7px">
<label class="">
Customers:
</label>
</div>
<div class="col-md-10">
<div class="col-md-3">
<select class=" form-control" ng-change="self.selectedCustomer()" name="Id" ng-model="self.selected" ng-options="item.Id as item.FullName for item in self.customers"></select>
</div>
</div>
<div class="col-md-10 form-group">
<hr style="border-color: #000080" />
<fieldset data-bind="with: currentCustomer">
<legend>Customer:</legend>
<label for="customerName">Name:</label>
<br/>
<input class="form-control" id="customerName" value="{{self.selectedFirstName}}" />
<label for="customerPhone">Tell:</label>
<br/>
<input id="customerPhone" class="form-control" value="{{self.selectedLastName}}" />
<br />
<button class=" btn btn-default" id="saveButton" ng-click="self.save()">Save</button>
</fieldset>
</div>
</div>
I think EveryThing Is ok
but when I save it,nothing Saved

Your code creates a new empty EntityManager with each query and save operation. Instead, you should create a single EntityManager in your TestService, and use it for all query and save operations.
var services = function (http) {
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
var dataService = new breeze.DataService({
serviceName: 'breeze/Zza',
hasServerMetadata: false
});
var manager = new breeze.EntityManager(
{
dataService: dataService
});
this.getBybreeze = function (successed) {
var entityQuery = breeze.EntityQuery;
return entityQuery.from('Customers').using(manager).execute().then(successed);
}
this.saveByBreeze = function () {
manager.saveChanges().catch(function (error) { alert("Failed save to server: " + error.message); });
}
}
services.$inject = ["$http"];
app.service("TestService", services);

Related

Problem with upload file with a formGroup

I am using angular to make a register form include some information(name, email, password, and avatar). Backend I am using NodeJS and MongoDB to store information. About backend I already wrote register API OK. I tested on postman, It's worked for backend!!
But in angular client, when I input information from my register form, It's appear error, I am using formData to send input form to Backend API.
I am using formGroup to send my usersystem object include (name, role, email, password, and avatar)
Here is my html file.
<div class="common-form float_left ">
<form [formGroup]="dialogRegisterUserSysForm" >
<div class="field_wrapper box FlowupLabels">
<label class="label">NAME</label>
<div class="field fl_wrap pad-top-0">
<input type="text" name="name" formControlName="name" maxlength="255" placeholder="Enter user system name" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="clr"></div>
</div>
<div class="field_wrapper box FlowupLabels">
<label class="label">PASSWORD</label>
<div class="field fl_wrap pad-top-0">
<input type="password" id="illness-name" class="input-big hc_name fl_input ui-autocomplete-input" name="password" formControlName="password" maxlength="255" placeholder="Please enter a password" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="error_field" id="testResultsErrors"></div> <div class="clr"></div>
</div>
<div class="field_wrapper box FlowupLabels">
<label class="label">EMAIL</label>
<div class="field fl_wrap pad-top-0">
<input type="text" id="illness-name" class="input-big hc_name fl_input ui-autocomplete-input" name="email" formControlName="email" maxlength="255" placeholder="Enter an email." autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="error_field" id="testResultsErrors"></div> <div class="clr"></div>
</div>
<div>
<label>Upload Avatar</label>
<input (change)="onFileSelect($event.target)" type="file" formControlName="avatar" class="form-control">
</div>
<div class="save-cancel-btngrp-wrap">
<div class="cancel-link switchToViewMode" style="float: right">
<a (click)="matDialogRef.close(dialogRegisterUserSysForm)" class="switchToViewMode btn flat">CANCEL</a>
</div>
<div *ngIf="action =='new'" class="cancel-link switchToViewMode" style="float: right">
<a (click)="matDialogRef.close(['save',dialogRegisterUserSysForm])" class="switchToViewMode btn flat">SAVE</a>
</div>
</div>
</form>
</div>
In this form, the avatar is file input, I wrote “onFileSelect(input)” method.
onFileSelect(input) {
var fInput = input.files[0];
var fileName = fInput.name;
alert(fileName);
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (e: any) => {
alert("Result: " + e.target.result);
this.userSys.avatar = e.target.result;
// reader.readAsDataURL(input.files[0]);
}
// this.userSys.avatar = e.target.result;
reader.readAsDataURL(input.files[0]);
}
}
And below is my ts file.
import { FormBuilder, FormGroup } from '#angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '#angular/material';
import { UserSysService } from '../usersys.service';
import { UserSysModel } from '../usersys.model';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
#Component({
selector : 'usersys-form-dialog',
templateUrl : './usersys-form.component.html',
styleUrls : ['./usersys.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class UserSysFormDialogComponent
{
action: string;
userSys: UserSysModel; // Medical report model
dialogRegisterUserSysForm: FormGroup;
dialogTitle: string;
/**
* Constructor
*
* #param {MatDialogRef<MedicalReportFormDialogComponent>} matDialogRef
* #param _data
* #param {FormBuilder} _formBuilder
*/
constructor(
// private _mrReportService: HealthMedicalReportService,
public matDialogRef: MatDialogRef<UserSysFormDialogComponent>,
#Inject(MAT_DIALOG_DATA) private _data: any,
private _formBuilder: FormBuilder
)
{
// this.dialogTitle = 'Add New Medical Report';
// set default here
this.action = this._data.action;
if(this.action === 'edit'){
this.dialogTitle = 'Edit User System';
this.userSys = _data.userSys;
}else{
this.dialogTitle = 'Register new User System';
this.userSys = new UserSysModel({});
}
this.dialogRegisterUserSysForm = this.createUserSystemDialogForm();
}
onFileSelect(input) {
var fInput = input.files[0];
var fileName = fInput.name;
alert(fileName);
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (e: any) => {
alert("Result: " + e.target.result);
this.userSys.avatar = e.target.result;
// reader.readAsDataURL(input.files[0]);
}
// this.userSys.avatar = e.target.result;
reader.readAsDataURL(input.files[0]);
}
}
/**
* Create UserSystem form
*
* #returns {FormGroup}
*/
createUserSystemDialogForm(): FormGroup
{
return this._formBuilder.group({
email : [this.userSys.email],
password : [this.userSys.password],
name : [this.userSys.name],
avatar : [this.userSys.avatar]
});
}
}
Below is image of my register form:
But I got the error “fakepath”, I cannot post this form to the server.
I think my english is not good so may be my explain is so hard to understand.
Thanks you so much
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script>
window.onload = function () {
document.getElementById("uploadfile").disabled = true;
document.getElementById("excelData").disabled = false;
};
document.addEventListener('keydown', function (e) {
if (e.which == 116) {
window.onbeforeunload = function () {
window.onbeforeunload = null;
$(".se-pre-con").fadeIn("slow");
}
}
}, false);
$(document).ready(function () {
$(".se-pre-con").fadeOut("slow");;
});
function LoadPreloder() {
$(".se-pre-con").fadeIn("slow");;
}
function UnloadPreloder() {
$(".se-pre-con").fadeOut("slow");;
}
function enableDisable() {
var FileSelectedValue = null;
var ClassSelected = 0;
FileSelectedValue = document.getElementById("excelData").value;
ClassSelected = document.getElementById("SelectedClass").value;
//alert(ClassSelected);
if (document.getElementById("excelData").files.length) {
// alert("File is Selected !!");
document.getElementById("uploadfile").disabled = false;
}
else if (!document.getElementById("excelData").files.length) {
//alert("No File Selected !");
document.getElementById("uploadfile").disabled = true;
}
}
</script>
#section AngularScripts{
<script type="text/javascript">
var schoolStuff = angular.module("schoolStuff", ['lr.upload']);
schoolStuff.controller("downloadDataformateController", ['$scope', 'upload', '$http', function ($scope, upload, $http) {
$http.get('#Url.Action("GetStandardDivisionList", "Collection")')
.then(function (response) {
$scope.Standard_Mapping_Division = response.data;
// $scope.Standard_Mapping_DivisionId = $scope.Standard_Mapping_Division[0].Standard_Mapping_DivisionId;
$scope.dataType = [
{ "dataTypeId": "1", "dataTypeValue": "Student" },
{ "dataTypeId": "2", "dataTypeValue": "Teacher" }
];
$scope.dataTypeId = $scope.dataType[0].dataTypeId;
$scope.showdragdrop = null;
});
$scope.uploadExcel = function () {
LoadPreloder();
if ($scope.dataFile != undefined) {
upload({
url: '#Url.Action("PostExcelStudent", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
typeId: $scope.dataTypeId,
dataFile: $scope.dataFile
}
}).then(function (response) {
alert(response.data.Message);
$scope.UploadedStudentData = response.data.studentsdata;
UnloadPreloder();
});
}
}
$scope.changeme = function () {
//alert($scope.showdragdrop);
//enableDisable();
$scope.showdragdrop = 1;
// alert($scope.showdragdrop);
}
$scope.uploadStudentData = function () {
LoadPreloder($scope.UploadedStudentData);
console.log()
$http({
url: '#Url.Action("UploadStudentData", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
studentData: $scope.UploadedStudentData
}
}).then(function (response) {
$scope.InsertedStudentData = response.data.studentsdata;
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'slow');
//console.log(response);
//alert(response.data.Message);
//alert(response.data.teachersdata);
//alert(response.data.Success);
$scope.InsertedStudentData = response.data.studentsdata;
if (response.data.Success != 0) {
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'fast');
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedTeacherDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
}
else if (response.data.Success == 0) {
alert(response.data.Message);
UnloadPreloder();
}
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedStudentDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
UnloadPreloder();
});
}
}]).directive('uploadFile', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var file_uploaded = $parse(attrs.uploadFile);
element.bind('change', function () {
scope.$apply(function () {
file_uploaded.assign(scope, element[0].files[0]);
});
});
}
};
}]);
</script>
}
Remove formControlName form file input then in your onload function set the value of avatar control. You need a instance of ChangeDetectorRef as well.
this.formGroup.patchValue({
avatar: reader.result
});
// Mark dirty
this.cdRef.markForCheck();
Note: In this approach as a value you'll have BASE64 hash which you should decrypt on the server side.

How to display factory method value in view using angularJS

Hi,am getting Json data as per my need,when injecting factory to
controller that data I am unable to show in view in angularJs i.e
correct answer div in UI,I will be thankful if anyone can help to me
Controller code:
public JsonResult displayCorrectAnswer()
{
Db.Configuration.ProxyCreationEnabled = false;
var rs = from q in Db.questions
join a in Db.answers on q.Qid equals a.questionID
where a.isAnswer == "1"
select new { a.answer1 };
return Json(rs, JsonRequestBehavior.AllowGet);
}
>Json Data:
[
{"answer1":"4"},
{"answer1":"Modi"}
]
>Script Code:
var myApp = angular.module("QuestionDisplayModule", [])
.controller("QuestionDisplayController", function ($scope, $http, $log, answerService) {
$http.get("displayQuestion").then(function(response)
{
$log.info(response);
$scope.questionsData = response.data;
})
$scope.answerCheck = answerService.choose();
})
myApp.factory("answerService", function ($http) {
var CorrectAnswers = {};
CorrectAnswers.choose = function () {
return $http.get("displayCorrectAnswer").success(function (response) {
response.data;
})
}
return CorrectAnswers;
});
>View Code:
<body ng-app="QuestionDisplayModule">
<form>
<div ng-controller="QuestionDisplayController">
<div ng-repeat="q in questionsData" style="border:groove 1px green">
<h4 style="color: darkmagenta">{{q.QText}}</h4>
<p ng-repeat="a in q.answer1" style="color: cadetblue"><input type="radio" name="answers+{{$parent.$index}}" ng-model="q.selectedAns" value="{{a.option1}}" />{{a.option1}}</p>
<div ng-show="q.selectedAns">your answer is : {{q.selectedAns}}</div>
<div > correct Answer is : {{answerCheck.answer1}}</div>
</div>
</div>
</form>
</body>
var myApp = angular.module("QuestionDisplayModule", [])
.controller("QuestionDisplayController", function ($scope, $http, $log, answerService) {
$http.get("displayQuestion").then(function(response)
{
$log.info(response);
$scope.questionsData = response.data;
})
$scope.answerCheck = answerService.choose().then(function(response) {
$scope.answerCheck = response;
});
})
myApp.factory("answerService", function ($http) {
var CorrectAnswers = {};
CorrectAnswers.choose = function () {
return $http.get("displayCorrectAnswer")
});
>

Get list of data into HTML select from a controller in JavaScript

I'm trying to get data into HTML select with this code:
HTML:
<div ng-controller="Manufacturer">
<select ng-model="myManufacturer" ng-options="Manufacturer.name for Manufacturer in Manufacturers" class="form-control"></select>
</div>
JS:
angular.module('MyApp')
.controller('Manufacturer', ['$scope', function ($scope) {
$scope.CarManufacturer = null;
$.post("/Data/GetAllManufacturers");
$scope.Manufacturers = $.post.Data;
alert($scope.CarManufacturer);
// $scope.Manufacturers = [
// { name: 'Audi' , id: 1 },
// { name: 'Volvo', id: 2 },
// { name: 'BMW', id: 3 },
// { name: 'Skoda', id: 4 },
// { name: 'Siat', id: 5 }
//];
$scope.myManufacturer = $scope.Manufacturers[1]; // red
}]);
CONTROLLER:
public List<string> GetAllManufacturers()
{
dbCarEntities us = new dbCarEntities();
List<string> asd = us.CarManufacturers.Select(x => x.Name).ToList();
return asd;
}
Explanation:
I have an HTML select. I want to fill it with a list from my SQL table with Model Entity framework. So I need to go to a function and get back the list.
I tried also with JSON. It doesn't work either.
got it!!
angular.module('MyApp') // extending from previously created angularJS module in the First part
.controller('Part5Controller', function ($scope, LocationService) {
// expained about controller in Part2 // Here LocationService (Service) Injected
$scope.CountryID = null;
$scope.StateID = null;
$scope.CountryList = null;
$scope.StateList = null;
$scope.StateTextToShow = "Select State";
$scope.Result = "";
// Populate Country
LocationService.GetCountry().then(function (d) {
$scope.CountryList = d.data;
}, function (error) {
alert('Error!');
});
// Function For Populate State // This function we will call after select change country
$scope.GetState = function () {
$scope.StateID = null; // Clear Selected State if any
$scope.StateList = null; // Clear previously loaded state list
$scope.StateTextToShow = "Please Wait..."; // this will show until load states from database
//Load State
LocationService.GetState($scope.CountryID).then(function (d) {
$scope.StateList = d.data;
$scope.StateTextToShow = "Select State";
}, function (error) {
alert('Error!');
});
}
// Function for show result
$scope.ShowResult = function () {
$scope.Result = "Selected Country ID : " + $scope.CountryID + " State ID : " + $scope.StateID;
}
})
.factory('LocationService', function ($http) { // explained about factory in Part2
var fac = {};
fac.GetCountry = function () {
return $http.get('/Data/GetCountries')
}
fac.GetState = function (countryID) {
return $http.get('/Data/GetStates?countryID='+countryID)
}
return fac;
});
in $http.get we can put how many arguments we want.
in the controller :
public JsonResult GetCountries()
{
List<Country> allCountry = new List<Country>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
}
return new JsonResult { Data = allCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
// Fetch State by Country ID
public JsonResult GetStates(int countryID)
{
List<State> allState = new List<State>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allState = dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
}
return new JsonResult { Data = allState, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and finally HTML view:
<div ng-controller="Part5Controller">
Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
<option value="">Select Country</option>
</select>
State : <select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList">
<option value="">{{StateTextToShow}}</option>
</select>
<input type="button" value="Get Selected Values" ng-click="ShowResult()"/>
<div style="padding:10px; font-weight:bold; border:1px solid #f3f3f3">
{{Result}}
</div>
</div>
#section scripts{
<script src="~/Scripts/AngularController/Part5Controller.js"></script>
}

Accessing KO component fields in viewmodel

I have created my first KO component :
components.js
ko.components.register('team-dropdown', {
viewModel: function (params) {
var self = this;
self.teamNames = ko.observableArray([]);
$.ajax({
url: 'http://footballcomps.cloudapp.net/Teams',
type: 'get',
contentType: 'application/json',
success: function (data) {
$.each(data['value'], function (key, value) {
self.teamNames.push(value.TeamName);
});
console.dir(self.teamNames);
},
error: function (err) {
console.log(err);
}
});
self.selectedTeam = ko.observable();
},
template: { require: 'text!components/team-dropdown.html' }
});
team-dropdown.html
<div id="teams" class="inputBlock form-group">
<select class="form-control" name="teamName" data-bind="options: teamNames, value:selectedTeam"></select>
<label id="lblHomeTeam" data-bind="text: selectedTeam"></label>
And here is my view where I want to use the component :
<div class="row" id="divFixture">
<div class="col-md-4">
<div class="panel panel-info">
<div class="panel-heading">
<h2 class="panel-title">Add new fixture</h2>
</div>
<div class="panel-body">
<form data-bind="submit: fixture.addFixture">
<div class="form-group">
<team-dropdown />
</div>....
</form>
And my stripped down view model :
define(['knockout', 'knockout.validation', 'common', 'components'], function (ko) {
return function fixtureViewModel() {
function fixture(fixtureId, fixtureDate, homeId, homeName, homeBadge, homeScore, awayId, awayName, awayBadge, awayScore) {
this.FixtureId = fixtureId;
this.FixtureDate = fixtureDate;
this.HomeId = homeId;
this.HomeName = homeName;
this.HomeBadge = homeBadge;
this.HomeScore = homeScore;
this.AwayId = awayId;
this.AwayName = awayName;
this.AwayBadge = awayBadge;
this.AwayScore = awayScore;
}
var self = this;
self.Id = ko.observable();
self.FixtureDate = ko.observable();
self.HomeId = ko.observable();
self.HomeName = ko.observable();
self.HomeBadge = ko.observable();
self.HomeScore = ko.observable();
self.AwayId = ko.observable();
self.AwayName = ko.observable();
self.AwayBadge = ko.observable();
self.AwayScore = ko.observable();
self.selectedTeam = ko.observable();
self.addFixture = function() {
//how do I reference the selected item from my component here?
};
});
How do I reference the item I have selected in my component in self.addFixture?
Since the team-dropdown is meant to be a reusable component, you should provide a way to bind to it. As you have it, it is a standalone control, the outside world cannot interact with it except through the observables you have defined which doesn't make it very flexible.
I would add parameters to it where you can set what observables to bind to the value. Your fixtures has a selectedTeam property so that seems like a likely candidate.
ko.components.register('team-dropdown', {
viewModel: function (params) {
var self = this,
teamNames = ko.observableArray([]),
// default to a local observable if value not provided
selectedTeam = params.value || ko.observable();
// you probably don't want others to directly modify the teamNames array
self.teamNames = ko.pureComputed(teamNames);
self.selectedTeam = selectedTeam;
$.ajax({
url: 'http://footballcomps.cloudapp.net/Teams',
type: 'get',
contentType: 'application/json',
success: function (data) {
$.each(data['value'], function (key, value) {
// push to the local `teamNames` array
teamNames.push(value.TeamName);
});
console.dir(teamNames);
},
error: function (err) {
console.log(err);
}
});
},
template: { require: 'text!components/team-dropdown.html' }
});
Then set the parameter when you use the component:
<form data-bind="submit: fixture.addFixture">
<div class="form-group">
<team-dropdown params="value: fixture.selectedTeam" />
</div>
</form>
The selected value should now be set in the selectedTeam of your fixture, so you can just use that.
self.addFixture = function() {
var selectedTeam = self.selectedTeam(); // should have the value
};

ngClick not firing in nested ngRepeat filled with data from $http.post()

I have an AngularJS app to search for journeys. In the part of the problem I am trying to show all available countries per region. The idea is that when you click a country, a function has to be executed. But it never fires...
Any help?
View
<div id="headersearch" ng-controller="ProductSearchController">
<div id="headersearchContainer">
<input id="tripchoise" class="field" type="text" placeholder="Hoe ver wil je gaan?" ng-model="country" ng-change="switchView('countries')" ng-blur="switchView('')" ng-focus="switchView('countries')" />
<div id="triptypechoise">
<div class="triptype" ng-class="{active: filter=='single'}" title="Singlereizen" ng-click="switchFilter('single')"><img src="/Resources/Images/Layout/singlereis.png" alt="Singlereizen" /></div>
<div class="triptype" ng-class="{active: filter=='custom'}" title="Maatwerkreizen" ng-click="switchFilter('custom')"><img src="/Resources/Images/Layout/maatwerk.png" alt="Maatwerkreizen" /></div>
<div class="triptype" ng-class="{active: filter=='group'}" title="Groepsreizen" ng-click="switchFilter('group')"><img src="/Resources/Images/Layout/groepsreis.png" alt="Groepsreizen" /></div>
</div>
<div id="tripdeparturedatechoise" class="field arrow">
{{date}}
</div>
</div>
<div id="headersearchButton">
<span>ZOEK</span>
</div>
<div class="clear"></div>
<input type="text" class="datepicker datehide" id="searchdepartureDate" ng-model="date" datepicker/>
<div id="searchList" ng-class="{hide:view==''}">
<div class="loadingproducts" data-ng-show="loading">Loading products...</div>
<article class="searchentry" ng-show="view=='countries'">
<div class="" ng-repeat="region in regions">
<p>{{region.Name}}</p>
<ul>
<li ng-repeat="country in region.Countries">
<a ng-click="test()">{{country.Name}}</a>
</li>
</ul>
</div>
</article>
</div>
</div>
CONTROLLER
SearchApp.controller("ProductSearchController", function ($scope, $http) {
$scope.date = "Vertrek";
$scope.filter = "single";
$scope.view = "";
$scope.country = "";
$scope.switchFilter = function (filter) {
if ($scope.filter != filter) {
$scope.filter = filter;
$scope.search();
}
}
$scope.switchView = function (view) {
if ($scope.view != view)
$scope.view = view;
if ($scope.view != "" && $scope.view != "countries")
$scope.search();
}
$http.post("/AVProductList/GetCountriesByRegionAsync")
.success(function (response) {
$scope.regions = response.regions;
});
$scope.search = function () {
$scope.loading = true;
$http.post("/AVProductList/SearchProductsHeader?view="+ $scope.view +"&filter=" + $scope.filter, { SearchParameters: {Country: $scope.country}})
.success(function (data) {
if ($scope.filter == "custom")
$scope.trips = data.results;
else {
if ($scope.view == "trips")
$scope.trips = data.grouped.RoundtripgroupCode.doclist.docs;
else if ($scope.view == "departures")
$scope.trips = data.response.docs;
}
});
};
$scope.changeDate = function () {
if (isValidDate($scope.date)) {
$scope.view = "departures";
$scope.search();
}
else {
$scope.date = "Vertrek";
$scope.view = "trips";
}
}
$scope.selectCountry = function (name, code) {
$scope.countrycode = code;
$scope.country = name;
$scope.view = isValidDate($scope.date) ? "departures" : "trips";
$scope.search();
}
$scope.test = function () {
alert("Hoi");
}
});
Json result example of
$http.post("/AVProductList/GetCountriesByRegionAsync")
.success(function (response) {
$scope.regions = response.regions;
});
{
regions:[
{
Name:"Asia",
Countries:
[
{
Name: "China",
Code: "CH"
}
,...
]
}
,...
]
}
I made a stupid mistake:
The ngBlur on "tripchoise" was fired before the ngClick.

Categories