Я пытаюсь построить доказательство концепции приложения с помощью AngularJS и Jaydata. Я свободно слежу за шаблоном MVC на домашней странице AngularJS (http://angularjs.org/) в разделе «Подключить бэкэнд». Вместо Firebase я использую WebSQL через поставщиков Jaydata.Непостоянное поведение в представлениях AngularJS, заполненных Jaydata
У меня есть база данных WebSQL под названием InspecTechDB с двумя таблицами, организациями и клиентами. Существует связь между родителями и дочерними элементами между ними в OrganizationID. Это из моей модели:
$data.Entity.extend('Customer', {
'CustomerID': { 'key': true, 'type': 'Edm.Guid', 'nullable': false },
'OrganizationID': { 'type': 'Edm.Guid', 'nullable': false, 'required': true },
'CustomerName': { 'type': 'Edm.String' },
'Organization': { 'type': 'Organization', 'inverseProperty': '$$unbound' }
});
$data.Entity.extend('Organization', {
'OrganizationID': { 'key': true, 'type': 'Edm.Guid', 'nullable': false, 'required': true },
'OrganizationName': { 'type': 'Edm.String' },
'Customers': { 'type': 'Array', 'elementType': 'Customer', 'inverseProperty': '$$unbound' }
});
$data.EntityContext.extend('InspecTechDB', {
'Customers': { type: $data.EntitySet, elementType: Customer },
'Organizations': { type: $data.EntitySet, elementType: Organization }
});
У меня есть 3 вида шаблона: OrganizationIndex.html, CustomerIndex.html и CustomerEdit.html. CustomerEdit.html это один У меня возникли проблемы с:
<form name="myForm">
<div class="form-group">
<label>OrganizationID</label>
<input type="text" class="form-control" placeholder="OrganizationID" name="OrganizationID" ng-model="customer.OrganizationID" required>
<span ng-show="myForm.name.$error.required" class="help-inline">
Required
</span>
</div>
<div class="form-group" ng-class="{error: myForm.name.$invalid}">
<label>Name</label>
<input type="text" class="form-control" name="CustomerName" ng-model="customer.CustomerName" required>
<span ng-show="myForm.name.$error.required" class="help-inline">
Required
</span>
</div>
</form>
Я включил весь свой JS файл здесь:
var app = angular.module('AngularJaydataApp', ['ngRoute', 'jaydata']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'OrganizationIndex',
templateUrl: 'OrganizationIndex.html'
})
.when('/CustomerIndex/:id', {
controller: 'CustomerIndex',
templateUrl: 'CustomerIndex.html'
})
.when('/CustomerEdit/:id', {
controller: 'CustomerEdit',
templateUrl: 'CustomerEdit.html'
})
.otherwise({
redirectTo: '/'
});
});
var localDB = new InspecTechDB({
name: 'local',
databaseName: 'InspecTech'
});
app.controller('OrganizationIndex', function ($scope, $data){
//wait until the localDB is ready, then get the Organizations
$.when(localDB.onReady())
.then(function() {
$scope.inspectechdb = localDB;
$scope.organizations = localDB.Organizations.toLiveArray();
});
});
app.controller('CustomerIndex', function ($scope, $data, $routeParams) {
$.when(localDB.onReady())
.then(function() {
$scope.inspectechdb = localDB;
$scope.Customers = $scope.inspectechdb
.Customers
.filter('OrganizationID', '==', $routeParams.id)
.toLiveArray();
});
});
app.controller('CustomerEdit', function ($scope, $data, $routeParams) {
var customerID = $routeParams.id;
$.when(localDB.onReady())
.then(function() {
$scope.inspectechdb = localDB;
$scope.inspectechdb.Customers.single(function (customer) {
return customer.CustomerID == this.Id;
},
{Id: customerID},
function (customer) {
$scope.customer = customer;
console.dir(customer);
});
});
console.log('this entry s/b after the customer console entry');
});
Я могу успешно перейти к каждому из видов и заполнения OrganziationList.html из моей базы данных, как показано в приведенном выше коде. Я установил список «Организация», чтобы при щелчке записи «Организация» в моем представлении, представление CustomerIndex.html загружается и привязывается к моему списку клиентов. Это прекрасно работает. Я также настроил его так, чтобы, щелкнув запись клиента в представлении CustomerIndex, загрузилось представление CustomerEdit.html, и здесь я потерялся. Представление выглядит просто отлично, но форма не связана при загрузке представления, и я понимаю, почему (я думаю). Кажется, что b/c угловое связывает форму перед моим $ scope.customer заполняется. Свидетельством этого является лог консоли:
эту запись с/б после bind.js входа консоли клиента: 68
Клиент
Мой вопрос заключается в следующем: Почему OrganzationList и Представления CustomerList заполняются правильно, а в форме CustomerEdit нет и что можно сделать по этому поводу?
UPDATE Для тех, кто заинтересован, я сделал его работу, изменяя контроллер CustomerEdit за принятый ответ:
app.controller('CustomerEdit', function ($scope, $data, $routeParams) {
var customerID = $routeParams.id;
$.when(localDB.onReady())
.then(function() {
$scope.inspectechdb = localDB;
$scope.inspectechdb.Customers.single(function (customer) {
return customer.CustomerID == this.Id;
},
{ Id: customerID },
function (customer) {
$scope.$apply(function() {
$scope.customer = customer;
});
});
});
});
Благодарим за информацию. В этом есть смысл. «Лучше всего было бы передать объект вместо его загрузки, так как он уже загружен». Я изначально настроил его таким образом, но обновление страницы приведет к тому, что моя форма будет очищена, поэтому я подумал, что с помощью $ routeParams и повторной выборки из db я мог бы обойти это. – agileMike