Редактирование CRUD с помощью JayData и AngularJs

2 user517406 [2014-03-19 23:56:00]

Я пытаюсь создать базовое приложение CRUD с использованием JayData, AngularJS и OData Web Api. Я дошел до создания представления "Список" и вида "Редактировать", и, щелкнув параметр "Редактировать" для элемента в представлении "Список", он успешно перенаправляется в представление "Редактировать" и заполняется, как ожидалось. Однако, когда я вернусь к представлению "Список" и выберите последующие опции "Редактировать", представление "Редактировать" не будет заполнено. Вот мой соответствующий Угловой код:

EDIT: Вот мой полный код, по просьбе:

app.js:

    var app = angular.module("app", ["localization", "ngResource", "ngRoute", "jaydata"]).
    config(function ($routeProvider, $locationProvider) {
        $routeProvider.
            when('/Admin/Fixtures/List', { controller: FixtureListController, templateUrl: '/Content/Templates/Fixtures.html' }).
            when('/Admin/Fixtures/Add', { controller: FixtureAddController, templateUrl: '/Content/Templates/FixtureAddEdit.html' }).
            when('/Admin/Fixtures/Edit/:fixtureId', { controller: FixtureEditController, templateUrl: '/Content/Templates/FixtureAddEdit.html' }).
            otherwise({ controller: TeamListController, redirectTo: 'Admin/Teams/List', templateUrl: '/Content/Templates/Teams.html' });
        $locationProvider.html5Mode(true); //will use html5 mode rather than hashbang where available
    });

var FixtureListController = function ($scope, $data) {

    $scope.fixtures = [];
    $scope.context = [];
    $scope.selectedFixture = null;

    $data.initService('http://lovelyjubbly.cloudapp.net/odata')
    .then(function (context) {
        $scope.context = context;
        $scope.fixtures = context.Fixtures.include('Stage').include('HomeTeam').
                                include('AwayTeam').include('City').toLiveArray();
    });

    $scope.delete = function () {

        //get id, can use this to get item from ng-repeat
        var emp = new lovelyjubblyWebApi.Models.Fixture({ FixtureId: this.fixture.FixtureId });

        $scope.context.Fixtures.remove(emp);
        $scope.context.saveChanges();
    };
};

//crud controllers
var FixtureAddController = function ($scope, $data) {

    $scope.fixtures = [];

    $data.initService('http://lovelyjubbly.cloudapp.net/odata')
    .then(function (context) {
        $scope.context = context;
        $scope.fixtures = context.Fixtures.toLiveArray();
        $scope.teams = context.Teams.toLiveArray();
        $scope.cities = context.Cities.toLiveArray();
        $scope.stages = context.Stages.toLiveArray();
    });

    $scope.save = function () {

        //prevents a separate post
        $scope.fixture.entityState = $data.EntityState.Modified;
        $scope.context.Fixtures.add($scope.fixture, true);
        $scope.context.saveChanges();

        //reset state
        $scope.context.stateManager.reset();
    };
};

var FixtureEditController = function ($scope, $data, $routeParams) {

    $scope.context = [];
    $scope.fixtures = [];
    $scope.teams = [];
    $scope.cities = [];
    $scope.stages = [];
    $scope.selectedFixture = null;
    $scope.fixture = null;


    $data.initService('http://lovelyjubbly.cloudapp.net/odata')
    .then(function (context) {
        $scope.context = context;
        $scope.fixtures = context.Fixtures.include('Stage').include('HomeTeam').
                                include('AwayTeam').include('City').toLiveArray();
        $scope.teams = context.Teams.toLiveArray();
        $scope.cities = context.Cities.toLiveArray();
        $scope.stages = context.Stages.toLiveArray();

        var emp = new lovelyjubblyWebApi.Models.Fixture({ FixtureId: $routeParams.fixtureId });

        $scope.context.Fixtures.filter('FixtureId', '==', $routeParams.fixtureId)
            .forEach(function (item) {
                emp.StageId = item.StageId;
                emp.CityId = item.CityId;
                emp.FixtureDate = item.FixtureDate;
                emp.HomeTeamId = item.HomeTeamId;
                emp.HomeTeamScore = item.HomeTeamScore;
                emp.AwayTeamId = item.AwayTeamId;
                emp.AwayTeamScore = item.AwayTeamScore;
            }).then(function (e)
            {
                $scope.fixture = emp;
            });

        $scope.save = function () {

            if ($scope.form.$valid) { //check for valid form

                var todo = $scope.context.Fixtures.attachOrGet({ FixtureId: $routeParams.fixtureId });
                todo.StageId = $scope.fixture.StageId;
                todo.CityId = $scope.fixture.CityId;
                //emp2.FixtureDate = $scope.fixture.FixtureDate;
                todo.FixtureDate = "10/10/2014 00:00";
                todo.HomeTeamId = $scope.fixture.HomeTeamId;
                todo.HomeTeamScore = $scope.fixture.HomeTeamScore;
                todo.AwayTeamId = $scope.fixture.AwayTeamId;
                todo.AwayTeamScore = $scope.fixture.AwayTeamScore;
                $scope.context.saveChanges();
            } else {
                alert("invalid form"); 
            }
        };
    });
};

Посмотреть список:

<table class="table table-striped table-condensed table-hover">
    <thead>
        <th>
            Fixture Id
        </th>
        <th>
            Fixture Date
        </th>
        <th>
            Stage
        </th>
        <th>
            City
        </th>
        <th>
            Home Team
        </th>
        <th>
            Score
        </th>
        <th>
            Away Team
        </th>
        <th>
            Score
        </th>
    </thead>
    <tbody>
        <tr ng-repeat="fixture in fixtures | orderBy:'FixtureId'" id="fixture_{{fixture.FixtureId}}">
            <td>{{fixture.FixtureId}}</td>
            <td>{{fixture.FixtureDate}}</td>
            <td>{{fixture.Stage.StageName}}</td>
            <td>{{fixture.City.CityName}}</td>
            <td>{{fixture.HomeTeam.TeamName}}</td>
            <td>{{fixture.HomeTeamScore}}</td>
            <td>{{fixture.AwayTeam.TeamName}}</td>
            <td>{{fixture.AwayTeamScore}}</td>
            <td>
                <a href="/Admin/Fixtures/Edit/{{fixture.FixtureId}}"><i class="glyphicon glyphicon-edit"></i></a>
                <a ng-click="delete()"><i class="glyphicon glyphicon-remove"></i></a>
            </td>
        </tr>
    </tbody>
</table>

Добавить/изменить вид:

<form name="form" class="col-xs-2" id="form" class="form-horizontal">
    <div class="control-group" ng-class="{error: form.StageName.$invalid}">
        <label class="control-label" for="StageName">Stage Team</label>
        <div class="controls">
            <select class="form-control" ng-model="fixture.StageId" ng-options="stage.StageId as stage.StageName for stage in stages" required>
                <option style="display:none" value="">Select</option>
            </select>
            <span ng-show="form.StageName.$dirty && form.StageName.$error.required">Stage required</span>
        </div>
    </div>
    <div class="control-group" ng-class="{error: form.CityName.$invalid}">
        <label class="control-label" for="CityName">City</label>
        <div class="controls">
            <select class="form-control" ng-model="fixture.CityId" ng-options="city.CityId as city.CityName for city in cities" required>
                <option style="display:none" value="">Select</option>
            </select>
            <span ng-show="form.CityName.$dirty && form.CityName.$error.required">City required</span>
        </div>
    </div>
    <div class="control-group" ng-class="{error: form.FixtureDate.$invalid}">
        <label class="control-label" for="BirthDate">Fixture Date</label>
        <div class="controls">
            <input type='text' class="form-control" ng-model="fixture.FixtureDate" name='FixtureDate' title="FixtureDate" />
        </div>
    </div>
    <div class="control-group" ng-class="{error: form.HomeTeamName.$invalid}">
        <label class="control-label" for="HomeTeamName">Home Team</label>
        <div class="controls">
            <select class="form-control" ng-model="fixture.HomeTeamId" ng-options="team.TeamId as team.TeamName for team in teams" required>
                <option style="display:none" value="">Select</option>
            </select>
            <span ng-show="form.HomeTeamName.$dirty && form.HomeTeamName.$error.required">Home Team required</span>
        </div>
    </div>
    <div class="control-group" ng-class="{error: form.HomeTeamScore.$invalid}">
        <label class="control-label" for="HomeTeamScore">Home Team Score</label>
        <div class="controls">
            <input type="text" class="form-control" placeholder="Score" ng-model="fixture.HomeTeamScore" id="HomeTeamScore" name="HomeTeamScore"  />
        </div>
    </div>
    <div class="control-group" ng-class="{error: form.AwayTeamName.$invalid}">
        <label class="control-label" for="AwayTeamName">Away Team</label>
        <div class="controls">
            <select class="form-control" ng-model="fixture.AwayTeamId" ng-options="team.TeamId as team.TeamName for team in teams" required>
                <option style="display:none" value="">Select</option>
            </select>
            <span ng-show="form.AwayTeamName.$dirty && form.AwayTeamName.$error.required">Away Team required</span>
        </div>
    </div>
    <div class="control-group" ng-class="{error: form.AwayTeamScore.$invalid}">
        <label class="control-label" for="AwayTeamScore">Away Team Score</label>
        <div class="controls">
            <input type="text" class="form-control" placeholder="Score" ng-model="fixture.AwayTeamScore" id="AwayTeamScore" name="AwayTeamScore" />
        </div>
    </div>
    <br />
    <div class="form-actions">
        <button ng-show="form.$valid" ng-click="save()" class="btn btn-primary">{{action}}</button>
        <a href="/Admin/Fixtures/List" class="btn btn-danger">Cancel</a>
    </div>
</form>

javascript angularjs odata asp.net-web-api jaydata


1 ответ


1 Remento [2014-03-22 18:42:00]

Это немного сложно, поскольку мы не видим кода для выбора, маршрутов или способов вызова контроллеров.

Однако я считаю, что создается только один экземпляр объекта FixtureEditController. Вы можете проверить это, добавив точку останова или консольный журнал в FixtureEditController.

Поэтому призыв к:

$data.initService('http://lovelyjubbly.cloudapp.net/odata') 

а также

var emp = new lovelyjubblyWebApi.Models.Fixture({ FixtureId: $routeParams.fixtureId });

производятся только один раз.

В контроллере редактирования. вам нужно будет определить, когда изменяется параметр маршрута, чтобы вы могли принять меры.

$scope.routeParams = $routeParams;
$data.initService('http://lovelyjubbly.cloudapp.net/odata')
.then(function (context) {
    $scope.$watch('$routeParams',function(routeParams){
        // this should run on any change in routeParams (regardless of the current state)
    },true);

Я не уверен, что просмотр routeParams - лучший подход, если контроллер редактирования наследуется от контроллера списка, тогда вы можете посмотреть "selectedFixture".