簡體   English   中英

如何在Angular的同一頁面上添加/編輯

[英]How can I Add/Edit on same page in Angular

我要在單頁上顯示兩種類型的數據,一種是“插入”表單,第二種是在Angular dataTables的幫助下顯示數據的位置,現在我想做的是單擊“編輯”時要顯示數據在“插入”表單字段中,還可以將“保存”按鈕從“保存”更改為“更新” ...我已經嘗試過了,但是雖然在控制台中顯示了數據,但是卻出現了此錯誤。

controller.js:1356 24
controller.js:1363 Colony 02 2
angular-1.4.8.js:12520 TypeError: Cannot set property 'colony_name' of undefined

注意:插入,刪除,顯示數據工作正常。

這是我的HTML PAGE

<div class="row-fluid" ng-controller="colony_Controller">
<div class="span12">

    <div class="span6">

        <!-- WIDGET START -->
        <div class="widget TwoWidgetsInOneFix">

            <!-- Widget Title Start -->
            <div class="widget-title">
                <h4><i class="icon-reorder"></i>Add Colony</h4>
                <span class="tools">
                    <a href="javascript:;" class="icon-chevron-down"></a>
                    <!-- <a href="javascript:;" class="icon-remove"></a> -->
                </span>
            </div>
            <!-- Widget Title End -->

            <!-- Widget Body Start -->
            <div class="widget-body">

                <form class="form-horizontal">

                    <div class="control-group">
                        <div class="small-bg-half">
                            <label class="control-label">Colony Name</label>
                            <div class="controls">
                                <input type="text" class="input-xlarge" id="" autofocus required name="colony_name"
                                ng-model="field.colony_name" > <!-- ng-->
                                <span class="help-inline" id="help-inline" style="color:red;"></span>
                            </div>
                        </div>
                    </div>

                    <div class="control-group">
                        <div class="small-bg-half">
                            <label class="control-label">Colony Type</label>
                            <div class="controls">
                                <select data-toggle="status" class="select select-default mrs mbm input-xlarge" name="colony_type" id="colony_type" ng-model="field.colony_type_id" required> <!-- ng -->
                                    <option value="">--Select Colony Type--</option>
                                    <option ng-repeat="colony in es_colony_type" value="{{colony.es_colony_type_id}}">{{colony.es_colony_type_name}}</option>

                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                            <button type="button" class="btn btn-success" ng-click="InsertData()"> <!-- ng -->
                            <i class="icon-plus icon-white"></i> Save</button>
                    </div>
                </form>

            </div>
            <!-- Widget Body End -->

        </div>
        <!-- WIDGET END -->

    </div>

    <div class="span6">

        <!-- WIDGET START -->
        <div class="widget TwoWidgetsInOneFix">

            <!-- Widget Title Start -->
            <div class="widget-title"> <!-- ng -->
                <h4><i class="icon-reorder"></i>List Of Colony</h4>
                <span class="tools">
                    <a href="javascript:;" class="icon-chevron-down"></a>
                    <!-- <a href="javascript:;" class="icon-remove"></a> -->
                </span>
            </div>
            <!-- Widget Title End -->

            <!-- <div id="alert-2" flash-alert active-class="in alert" class="fade">
                <strong class="alert-heading">Boo!</strong>
                <span class="alert-message">{{flash.message}}</span>
            </div> -->

            <!-- Widget Body Start -->
            <div class="widget-body">

                <div ng-controller="colony_Controller as Main_Module">
                    <table class="table table-striped table-bordered" align="center" datatable="" dt-options="Main_Module.dtOptions" dt-columns="Main_Module.dtColumns" class="row-border hover">
                    </table>
                </div>

            </div>

        </div>
        <!-- Widget Body End -->

    </div>
    <!-- WIDGET END -->

</div>

這是我的控制器

Main_Module.controller('colony_Controller', function add_house_Controller(flash, $window, $scope, $http, $compile, DTOptionsBuilder, DTColumnBuilder, bootbox, SimpleHttpRequest, DelMainRecPicRecUnlinkPic, message)
{   
            $http.get('http://localhost:3000/api/SELECT/es_colony_type').success(function(data)
    {
        $scope.es_colony_type = data.es_colony_type;
    });
    /********************************** FETCH DATA END *********************************/

    /********************************** INSERT DATA START ********************************/
    $scope.InsertData = function()
    {
        var values = $scope.field;

        SimpleHttpRequest.Insert('POST','INSERT', 'es_colony', values)
        .then(function successCallback(response)
        {
            if(!response.data.Error)
            {
                message.successMessageForInsert("<strong>Successfull !</strong> Colony Details Inserted");
                setTimeout(function()
                {
                    $window.location.reload();
                }, 3500);

                // flash.to('alert-1').success = 'Only for alert 1';                                
            }
            else
            {
                message.failedMessageForInsert("<strong>Error !</strong> Data Insertion Failed");
            }
        },
        function errorCallback(response)
        {
            message.failedMessageForInsert("<strong>Error!</strong> Data Insertion Failed !");
        });       
    };
    /********************************** INSERT DATA END **********************************/

    /********************************** DISPLAY DATA START *******************************/
    var vm = this;
    vm.dtOptions = DTOptionsBuilder
    .fromFnPromise(function()
    {
        return $http.get('http://localhost:3000/api/SELECT/es_colony')
        .then(function(response)
        {
            return response.data.es_colony;
        });
    })
    .withOption('order', [0, 'asc'])
    .withDisplayLength(5)
    .withPaginationType('simple_numbers')
    .withOption('createdRow', function(row, data, dataIndex)
    {
        $compile(angular.element(row).contents())($scope);
    })
    vm.dtColumns =
    [
        DTColumnBuilder.newColumn('es_colony_name').withTitle('Colony'),            
        DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable().withOption('width', '31%')
        .renderWith(function(data, type, full, meta)
        {
            return '<button class="btn btn-primary" ng-click="edit_records(' + data.es_colony_id + ')">' +
                   '<i class="icon-edit"></i> Edit' + '</button>&nbsp;' +
                   '<button class="btn btn-danger" ng-click="DeleteRecord(' + data.es_colony_id + ')">' +
                   '<i class="icon-remove icon-white"></i> Delete' + '</button>';
        })
    ];

    /********************************** DISPLAY DATA END *********************************/

    /********************************** DELETE DATA START ********************************/
    // $scope.hideRow = [];
    $scope.DeleteRecord = function(id)
    {
        bootbox.confirm("Are you sure you want to delete this Record ?", function (confirmation)
        {
            if(confirmation)
            {
                DelMainRecPicRecUnlinkPic.DeleteIt('', id, true, 'es_colony', 'es_colony_id')
                {
                    setTimeout(function()
                    {
                        $window.location.reload();
                    }, 3500);
                };
            }
        });
    };

    $scope.edit_records = function(id)
    {
        // PassId.id = id;
        console.log(id);

        SimpleHttpRequest.SelectByID('GET', 'SELECTBYID', 'es_colony', 'es_colony_id', id)
        .then(function successCallback(response)
        {
            var data = response.data.es_colony[0];

            console.log(data.es_colony_name, data.es_colony_type_id);    

            $scope.ufield.ucolony_name = data.es_colony_name;
            $scope.ufield.colony_type_id = data.es_colony_type_id;
        });
    };
    /********************************** DELETE DATA END **********************************/

});

在模板中,您具有ng-model="field.colony_name"的輸入,但是在您的控制器中,您從未定義$scope.field 您確實在$scope.InsertData函數中分配了值var values = $scope.field ,但這只會將values設置為undefined

嘗試通過將$scope.field = {}添加到控制器的開頭來初始化變量(對於初學者)。 這樣可以解決您遇到的錯誤。

這是可以幫助您的代碼。 HTML:

<div ng-app="myApp" ng-controller="MainCtrl">
   <fieldset  data-ng-repeat="choice in choices">          
      <input type="text" ng-model="choice.name" name="" placeholder="Enter mobile number"> <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
   </fieldset>
   <button class="addfields" ng-click="addNewChoice()">Add fields</button>           
   <div id="choicesDisplay">
      {{ choices }}
   </div>
</div>

Js:

var app = angular.module('myApp', []);    
app.controller('MainCtrl', function($scope) { 
    $scope.choices = [{id: 'choice1'}, {id: 'choice2'}];      
    $scope.addNewChoice = function() {
        var newItemNo = $scope.choices.length+1;
        $scope.choices.push({'id':'choice'+newItemNo});
    };

    $scope.removeChoice = function() {
        var lastItem = $scope.choices.length-1;
        $scope.choices.splice(lastItem);
    };

});

也是CSS:

fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;   
}
input[type="text"],
select{
    padding:5px;
}

HTML

<div ng-app="albumShelf">
    <div ng-controller="MainCtrl">
        <div style="float:left;">
            <select ng-options="b.title for b in albums" ng-model="currentAlbum" ng-change="onChange()">
              <option value="">New album...</option>
            </select>
        </div>

        <div style="float:left;">
            <form>
                <input type="text" ng-model="editing.title">
                <br>
                <input type="text" ng-model="editing.artist">
                <br>
                <input type="submit" value="{{ currentAlbum.title ? 'Update' : 'Save' }}" ng-click="addOrSaveAlbum()">
            </form>
        </div>
    </div>
</div>

Js:

var app= angular.module('myApp', [])
.controller('MainCtrl', ['$scope', function($scope/*, albumFactory*/) {
    $scope.editing = {};        
    $scope.albums = [
        { id: 1, title: 'Disorganized Fun', artist: 'Ronald Jenkees' },
        { id: 2, title: 'Secondhand Rapture', artist: 'MS MR' }
    ];
    $scope.addOrSaveAlbum = function() {
        if ($scope.currentAlbum) {
            $scope.currentAlbum.title = $scope.editing.title;
                $scope.currentAlbum.artist = $scope.editing.artist;
        }else {
            $scope.albums.push({ title: $scope.editing.title, artist: $scope.editing.artist });
        }            
            $scope.editing = {};
        };        
    $scope.onChange = function() {
        if ($scope.currentAlbum) {
            $scope.editing.title = $scope.currentAlbum.title;
            $scope.editing.artist = $scope.currentAlbum.artist;
        }else {
            $scope.editing = {};
        }
    };
}])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM