简体   繁体   English

如何在Angular的同一页面上添加/编辑

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

There are two types of data I'm displaying on single page, one is Insert form and second is where the data is displayed with the help of Angular dataTables, now what I want to do is when I click on Edit I wana display the Data within the Insert form Fields also change the Save button from Save to Update... I've tried it but I'm getting this error although its displaying the data in console. 我要在单页上显示两种类型的数据,一种是“插入”表单,第二种是在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

NOTE: Insert, Delete, Displaying Data is working fine. 注意:插入,删除,显示数据工作正常。

Here is my HTML PAGE 这是我的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>

Here is my Controller 这是我的控制器

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 **********************************/

});

In your template, you have an input with ng-model="field.colony_name" , but in your controller you never defined $scope.field . 在模板中,您具有ng-model="field.colony_name"的输入,但是在您的控制器中,您从未定义$scope.field You do assign the value var values = $scope.field inside the $scope.InsertData function, but that will just set values to undefined . 您确实在$scope.InsertData函数中分配了值var values = $scope.field ,但这只会将values设置为undefined

Try initializing the variable by adding $scope.field = {} to the beginning of your controller, for starters. 尝试通过将$scope.field = {}添加到控制器的开头来初始化变量(对于初学者)。 That will resolve the error you are getting. 这样可以解决您遇到的错误。

Here is the code that may help you. 这是可以帮助您的代码。 Html: 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: 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);
    };

});

Also CSS: 也是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 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: 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