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.
Related
I have a select item that the values (multi-select) can be populated in the controller. But when I populate the value in the controller, the select still shows as invalid since this field is required.
Markup as per below.
<div ng-controller="host.views.newAnnouncement.index as vm">
<div class="portlet light bordered" id="form_wizard_1">
<div class="portlet-title">
<div class="caption">
<i class=" icon-speech font-blue"></i>
<span class="caption-subject font-blue bold">
New Announcement
</span>
</div>
</div>
<div class="portlet-body">
<div class="col-md-12">
<div class="alert alert-danger" ng-show="vm.isInError">
<p ng-repeat="message in vm.errorMessages">{{message}}</p>
</div>
<ng-form name="vm.announcementForm">
<div class="form-group form-md-line-input form-md-floating-label no-hint"
ng-class="{'has-error': (vm.announcementForm.announcementTypes.$dirty || vm.isValidated) && vm.announcementForm.announcementTypes.$invalid}">
<select class="form-control" name="announcementTypes" id="announcementTypes"
ng-class="{'edited': vm.model.announcementType}"
ng-model="vm.model.announcementType"
ng-options="announcementType.id as announcementType.name for announcementType in vm.announcementTypes"
required></select>
<label for="announcementTypes">Announcement Type</label>
</div>
<div class="form-group form-md-line-input no-hint"
ng-class="{'has-error': (vm.announcementForm.audienceTypes.$dirty || vm.isValidated) && vm.announcementForm.audienceTypes.$invalid}">
<select class="form-control" name="audienceTypes" id="audienceTypes"
ng-class="{'edited': vm.model.audienceType}"
ng-model="vm.model.audienceType"
ng-options="audienceType.id as audienceType.name for audienceType in vm.audienceTypes"
ng-change="vm.onAudienceTypeChange()"
required></select>
<label for="audienceTypes">Audience Type</label>
</div>
<div class="form-group form-md-line-input no-hint"
ng-class="{'has-error': (vm.announcementForm.audiences.$dirty || vm.isValidated) && vm.announcementForm.audiences.$invalid}">
<select class="form-control" name="audiences" id="audiences"
ng-class="{'edited': vm.model.audiences}"
ng-model="vm.model.audiences"
ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'"
multiple required
style="min-height:300px;"></select>
<label for="audiences">Audience List <span ng-if="vm.model.audiences.length > 0">(Selected: {{vm.model.audiences.length}})</span></label>
</div>
<div class="form-group form-md-line-input form-md-floating-label no-hint"
ng-class="{'has-error': (vm.announcementForm.subject.$dirty || vm.isValidated) && vm.announcementForm.subject.$invalid}">
<input type="text" name="subject" class="form-control" ng-class="{'edited':vm.model.subject}" ng-model="vm.model.subject" maxlength="50" required>
<label>Subject</label>
</div>
<br />
<div class="form-group">
<label>Details</label>
<text-angular ta-text-editor-class="form-content" ta-html-editor-class="form-content" ng-model="vm.model.body"></text-angular>
</div>
<div class="row form-group col-md-12">
<label class="control-label">Attachement (zip)</label>
<input name="file" type="file" id="attachements" nv-file-select="" uploader="vm.fileUploader" accept=".zip"/>
</div>
</ng-form>
</div>
<hr />
<div class="row">
<div class="col-md-12">
<button type="button" class="btn default button-previous" ng-click="vm.back()">
<i class="fa fa-angle-left"></i> Back
</button>
<button type="button" class="btn green button-submit"
button-busy="vm.saving"
busy-text="#L("SavingWithThreeDot")"
ng-click="vm.submit()"
ng-disabled="vm.announcementForm.$invalid">
Submit
<i class="fa fa-check"></i>
</button>
</div>
</div>
</div>
</div>
Controller
(function () {
appModule.controller('host.views.newAnnouncement.index', [
'$scope', '$state', 'FileUploader', 'abp.services.app.hostAnnouncement', 'abp.services.app.hostSettings',
function ($scope, $state, FileUploader, announcementService, hostSettingsService) {
var vm = this;
vm.model = {
subject: '',
body: '',
announcementType: null,
audienceType: 0,
audiences: [],
feedbackId: null
};
vm.audienceList = [];
vm.announcementTypes = [
{ id: 0, name: 'General' },
{ id: 1, name: 'Penalty Invoice' },
{ id: 2, name: 'Other' }
];
vm.audienceTypes = [
{ id: 0, name: 'By Tenant' },
{ id: 1, name: 'By Store Category' },
{ id: 2, name: 'By Floor Location' },
{ id: 3, name: 'By Zone' }
];
vm.fileUploader = new FileUploader({
url: abp.appPath + 'AnnouncementDocument/UploadFileAsync',
filters: [
{
'name': 'enforceMaxFileSize',
'fn': function (item) {
return item.size <= 2097152; // 2 MiB to bytes
}
}
]
});
vm.submit = submit;
vm.back = back;
vm.onAudienceTypeChange = onAudienceTypeChange;
initialize();
vm.errorMessages = [];
vm.tenants = [];
vm.storeCategories = [];
vm.floorLocations = [];
vm.zones = [];
vm.announcementData = {
announcementId: null,
setAnnouncementId: function (announcementId) {
this.announcementId = announcementId;
}
}
function onAudienceTypeChange() {
vm.model.audiences = [];
if (vm.model.audienceType === 0) {
vm.audienceList = vm.tenants;
} else if (vm.model.audienceType === 1) {
vm.audienceList = vm.storeCategories;
} else if (vm.model.audienceType === 2) {
vm.audienceList = vm.floorLocations;
} else if (vm.model.audienceType === 3) {
vm.audienceList = vm.zones;
}
}
function initialize() {
vm.loading = true;
hostSettingsService.getAllSettings()
.success(function (result) {
_.each(result.storeCategories.split("|"), function (item) {
if (item !== "") {
vm.storeCategories.push({
name: item,
id: item
});
}
});
_.each(result.floorLocations.split("|"), function (item) {
if (item !== "") {
vm.floorLocations.push({
name: item,
id: item
});
}
});
_.each(result.zones.split("|"), function (item) {
if (item !== "") {
vm.zones.push({
name: item,
id: item
});
}
});
}).finally(function () {
announcementService.getTenants()
.success(function (result) {
vm.tenants = result;
vm.audienceList = vm.tenants;
}).finally(function () {
vm.loading = false;
autoSelectTenant($state.params);
});
});
}
function autoSelectTenant(stateParams) {
if (stateParams.tenantId && stateParams.feedbackId) {
vm.model.feedbackId = stateParams.feedbackId;
vm.model.audienceType = 0;
vm.model.audiences.push(stateParams.tenantId);
}
}
function submit() {
validate();
if (vm.isInError) return;
vm.saving = true;
vm.isValidated = true;
announcementService.createAnnouncementAsync(vm.model)
.success(function (announcementId) {
if (vm.fileUploader.queue.length > 0) {
vm.announcementData.setAnnouncementId(announcementId);
vm.fileUploader.uploadAll();
} else {
showSuccessNotification();
}
});
}
function back() {
$state.go('host.announcement');
}
function validate() {
vm.isInError = false;
vm.errorMessages = [];
if (vm.model.audiences.length < 1) {
vm.errorMessages.push("Please select an audience list.");
vm.isInError = true;
}
vm.isValidated = true;
}
vm.fileUploader.onBeforeUploadItem = function (fileItem) {
fileItem.formData.push(vm.announcementData);
};
vm.fileUploader.onCompleteAll = function () {
showSuccessNotification();
};
function showSuccessNotification() {
$state.go('host.announcement');
vm.saving = false;
abp.notify.success("Announcement has been successfully published.");
}
}
]);
})();
How do I programmatically set the selection values from the controller and make sure that the field is not invalid? The audiences value is being passes through the $state.params and I've added it to the vm.model.audiences array. But in the UI, vm.model.audiences is still marked as required even though it had values already.
EDIT : I've updated my question with full html and controller. For more clear understanding.
Try like this
var app = angular.module("app", []);
app.controller('mainCtrl', function($scope) {
var vm = this;
vm.model = {
audiences: []
};
vm.audienceList = [{
"name": "name1",
"id": 1
}, {
"name": "name2",
"id": 2
}, {
"name": "name3",
"id": 3
}];
vm.stateParams = {};
vm.stateParams.tenantId = 1;
vm.stateParams.feedbackId = 1;
vm.autoSelectTenant = function(stateParams) {
if (stateParams.tenantId && stateParams.feedbackId) {
vm.model.feedbackId = stateParams.feedbackId;
vm.model.audienceType = 0;
vm.model.audiences.push(stateParams.tenantId);
}
}
vm.autoSelectTenant(vm.stateParams);
vm.stateParams.tenantId = 2;
vm.stateParams.feedbackId = 2;
vm.autoSelectTenant(vm.stateParams);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />
<div ng-app="app" ng-controller="mainCtrl as vm">
<select ng-model="vm.model.audiences" ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'" multiple required></select>
</div>
Am new to angular JS. I have following check box and the data is coming from web service:
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]" type="checkbox" ng-checked="r.value">
{{r.conditions_name}}
</label>
In console.log value is perfectly right as per my requirements. How to push value to an array i.e., arr[] and stringify it. I tried code like this..
//To fetch Medical Conditions List
$scope.parameter = "{}";
$scope.class0 = "{}";
$http.get('http://192.168.1.129:8080/apartment//member/medical/conditions/list').then(function(response) {
$scope.MedicalConditions = response.data.list;
});
$scope.$watchCollection('ids', function(newVal) {
$scope.parameter.class0 = $scope.ids;
});
$scope.alertdata = function() {
var parameter = {
"first_name": $scope.first_name,
"role": [{
"role_id": 1,
"name": "Admin",
"details": "text"
}],
"associated": [{
"associated_id": 1,
"associated_name": "Parent",
"primary_member_id": 1
}],
"class0": $scope.ids
}
parameter = JSON.stringify(parameter);
May be this will help:
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.ids = {};
$scope.arr = {};
$scope.MedicalConditions = {};
$scope.MedicalConditions[0] = {};
$scope.MedicalConditions[0].value= true;
$scope.MedicalConditions[0].conditions_name= 'first value';
$scope.MedicalConditions[1] = {};
$scope.MedicalConditions[1].value= false;
$scope.MedicalConditions[1].conditions_name= 'seconde value';
$scope.$watchCollection('ids', function(newVal) {
$scope.parameter.class0 = $scope.ids;
});
$scope.parameter = {};
$scope.parameter.firstname = 'dummy name';
$scope.parameter.class0 = $scope.ids;
});
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Controller">
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]" type="checkbox" ng-checked="r.value" > {{ r.conditions_name}}
</label>
<br>
Parameter: {{parameter}}
</div>
</body>
</html>
Try like below...
var app = angular.module('exApp',[]);
app.controller('ctrl', function($scope){
$scope.ids = [];
$scope.arr = [];
$scope.checkSelected = [];
$scope.MedicalConditions = [{"conditions_name":"xxz","conditions_id":"1"}, {"conditions_name":"yyz","conditions_id":"2"}, {"conditions_name":"zzz","conditions_id":"3"}];
$scope.$watchCollection('ids', function(newVal) {
for (var i = 0; i < newVal.length; ++i) {
console.log(newVal[i]);
$scope.arr.push(newVal[i]);
}
});
$scope.checkAllR = function () {
$scope.checkAll = !$scope.checkAll;
if ($scope.checkAll) {
$scope.checkSelected = [];
angular.forEach($scope.MedicalConditions, function (checkR) {
checkR.check = $scope.checkAll;
$scope.checkSelected.push(checkR);
});
}
else {
$scope.checkSelected = [];
angular.forEach($scope.MedicalConditions, function (checkR) {
var idx = $scope.checkSelected.indexOf(checkR);
checkR.check = $scope.checkAll;
$scope.checkSelected.splice(idx, 1);
});
}
};
$scope.addChecked = function (checked) {
if ($scope.checkSelected == undefined || $scope.checkSelected == null) {
$scope.checkSelected = [];
}
var idx = $scope.checkSelected.indexOf(checked);
// delete if exists
if (idx > -1) {
$scope.checkSelected.splice(idx, 1);
checked.check = false;
}
// add
else {
$scope.checkSelected.push(checked);
checked.check = true;
}
$scope.checkAll = $scope.checkSelected.length == $scope.MedicalConditions.length ? true : false;
};
var parameter = {
"first_name": $scope.first_name,
"middle_name": $scope.middle_name,
//"class0": /*stringified data i.e., arr[] */
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="exApp" ng-controller="ctrl">
Select All : <input type="checkbox" name="checkbox" value="1" ng-checked="checkAll" ng-click="checkAllR()"><br>
<label ng-repeat="r in MedicalConditions">
<input type="checkbox" name="checkbox" class="check-nolabel" value="1" ng-checked="r.check" ng-click="addChecked(r)"> {{ r.conditions_name}}
</label><br><br>
{{checkSelected}}
</body>
Hope this helps.
<div ng-app="myApp" ng-controller="MyCtrl">
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]"
ng-init="ids[$index] = r.value"
type="checkbox">
{{r.condition}}
</label>
</div>
And here is your controller.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope){
$scope.ids = [];
$scope.MedicalConditions = [{
_id: 1,
value: true,
condition: 'Condition 1'
}, {
_id: 2,
value: false,
condition: 'Condition 2'
}, {
_id: 3,
value: true,
condition: 'Condition 3'
}];
});
JsFiddle
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]" type="checkbox" ng-change="valCh(r)"> {{r.conditions_name}}
</label>
Controller code will look like this :
var postApp = angular.module('EntityApp', []);
postApp.controller('EntityAppCntroller', function($scope, $http, $window, $timeout, $location) {
//To fetch Medical Conditions List
$http.get('http://111.222.444:8080/apartment//member/medical/conditions/list').then(function(response) {
$scope.MedicalConditions = response.data.list;
});
var list = [];
$scope.valCh = function(value) {
list.push(value);
JSON.stringify(list);
}
$scope.alertdata = function() {
var parameter;
parameter = {
"parameter": {
"first_name": $scope.first_name,
"medicalconditions": list
}
}
$http({
url: 'http://111.222.333:8080/apartment//save/member/details',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify(parameter)
}).success(function(data, status) {
if (data.status == 'success') {
alert("User Created");
$location.reload();
} else if (data.status == 'failure') {
alert("Some failure please try again later !!!");
}
});
};
});
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")
});
>
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);
Adding ng-controller on view causing Error: [ng:areq] Argument 'ValidationCtrl' is not a function, got undefined. Following are the code snippets:
profile.html
<div class="row" ng-controller="ValidationCtrl">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" placeholder="Enter your first name" class="form-control" name="firstname" ng-model="user.first_name">
<span class="error text-small block" ng-if="Form.first_name.$dirty && Form.first_name.$invalid">Last Name is required</span>
<span class="success text-small" ng-if="Form.first_name.$valid">Wonderful!</span>
</div>
</div>
</div>
app.js
var myApp = angular.module("MyApp",['ngResource','ngRoute','ui.router','ngMessages','ngResource','cfp.loadingBar','duScroll','ngAnimate','satellizer','pascalprecht.translate','ngCookies','oc.lazyLoad','ui.bootstrap','toastr'])
.config(['$stateProvider', '$urlRouterProvider','$authProvider','$ocLazyLoadProvider','JS_REQUIRES',function($stateProvider, $urlRouterProvider,$authProvider,$ocLazyLoadProvider,jsRequires){
$stateProvider
.state('app.profile', {
url: '/profile',
templateUrl: "views/profile.html",
title: 'Buttons',
resolve: loadSequence('flow','validationCtrl')
});
$ocLazyLoadProvider.config({
debug: false,
events: true,
modules: jsRequires.modules
});
function loadSequence() {
var _args = arguments;
return {
deps: ['$ocLazyLoad', '$q',
function ($ocLL, $q) {
var promise = $q.when(1);
for (var i = 0, len = _args.length; i < len; i++) {
promise = promiseThen(_args[i]);
}
return promise;
function promiseThen(_arg) {
if (typeof _arg == 'function')
return promise.then(_arg);
else
return promise.then(function () {
var nowLoad = requiredData(_arg);
if (!nowLoad)
return $.error('Route resolve: Bad resource name [' + _arg + ']');
return $ocLL.load(nowLoad);
});
}
function requiredData(name) {
if (jsRequires.modules)
for (var m in jsRequires.modules)
if (jsRequires.modules[m].name && jsRequires.modules[m].name === name)
return jsRequires.modules[m];
return jsRequires.scripts && jsRequires.scripts[name];
}
}]
};
}
}]);
validationCtrl.js
'use strict';
/**
* controller for Validation Form example
*/
myApp.controller('ValidationCtrl', ["$scope", "$state", "$timeout", "SweetAlert", function ($scope, $state, $timeout, SweetAlert) {
alert('validation');
$scope.master = $scope.myModel;
$scope.form = {
submit: function (form) {
var firstError = null;
if (form.$invalid) {
var field = null, firstError = null;
for (field in form) {
if (field[0] != '$') {
if (firstError === null && !form[field].$valid) {
firstError = form[field].$name;
}
if (form[field].$pristine) {
form[field].$dirty = true;
}
}
}
angular.element('.ng-invalid[name=' + firstError + ']').focus();
SweetAlert.swal("The form cannot be submitted because it contains validation errors!", "Errors are marked with a red, dashed border!", "error");
return;
} else {
SweetAlert.swal("Good job!", "Your form is ready to be submitted!", "success");
//your code for submit
}
},
reset: function (form) {
$scope.myModel = angular.copy($scope.master);
form.$setPristine(true);
}
};
}]);
and my config.constant.js
myApp.constant('JS_REQUIRES', {
scripts: {
'validationCtrl': ['controllers/validationCtrl.js']
}});
Thanks!