We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Binding grid in angular on user-driven events.

So....my company just got license for Syncfusion tools. We've decided to go the direction of using AngularJS with the SyncFusion JS controls. Looking through the forums and documentation...there isn't a lot of assistance in regard to angular and we're pretty much having to figure it out ourselves. So the scenario that I'm trying to solve for right now is as follows (all code examples will be at the bottom):

1. We have a WebAPI that has a POST that returns data (because we're passing an entire object in that's the reason for the post).
2. Front-end UI is MVC/AngularJS hybrid. So the page is loaded with MVC but the data-binding and service calls are in AngularJS.
3. This page is user-driven. The user sets some values and then clicks search.
4. The angular controller will path through the service and return data that should be bound to the SyncFusion Grid.
5. The grid should display the results.

** Problem **: It's not working. The data is being returned from the service appropriately and when assigning it to the datasource of the grid...it does not display the data. So my question is...how is the grid "supposed" to work in this situation.


** Code Examples **

--> controller.js
(function () {
    var app = angular.module('encoreApp');
    var logController = function ($scope, appGlobals, logService, lookupService) {
        appGlobals.validateUser();

        var onSearchComplete = function(data) {
            var results = data.LogResult;
            angular.forEach(results, function(item, index) {
                $scope.SearchResults.Items.push(item);
            });
            $scope.SearchResults.Count = results.length;
            $scope.isLoaded = true;
        };
        var onLoadComplete = function(data) {
            $scope.Severities = data;
        };
        var load = function() {
            lookupService.getSeverities().then(onLoadComplete);
        };

        $scope.Search = function() {
            logService.queryLogs($scope.logQuery).then(onSearchComplete);
        };
        $scope.logQuery = {};
        $scope.SearchResults = { Items: [], Count: 0 };
        $scope.isLoaded = false;

        load();
    };

    app.controller('logController', logController);
}());

--> Index.cshtml
<div data-ng-controller="logController">
    BeginDate: <input type="text" ng-model="logQuery.BeginDate">
    EndDate: <input type="text" ng-model="logQuery.EndDate">
    <!--LogSeverity: <input type="text" ej-dropdownlist e-fields-dataSource="Severities" e-fields-dataidfield="Id" e-fields-datavaluefield="Value" ng-model="logQuery.LogSeverity">-->
    LogSeverity <select ng-options="item.Id as item.Value for item in Severities" data-ng-model="logQuery.Severity"></select>
    MessageTitle: <input type="text" ng-model="logQuery.MessageTitle">
    UserId: <input type="number" ng-model="logQuery.UserId">
    MachineName: <input type="text" ng-model="logQuery.MachineName">
    MessageBody: <input type="text" ng-model="logQuery.MessageBody">
    PageStartIndex: <input type="number" ng-model="logQuery.PageStartIndex">
    PageEndIndex: <input type="number" ng-model="logQuery.PageEndIndex">
    <br />
    <button ej-button e-field-size="large" e-field-showroundedcorner="true" ng-click="Search()">Search</button>
    
    <div ej-grid e-datasource="SearchResults" ng-show="isLoaded">
        <div e-columns>
            <div e-column e-field="LogCreateDate" e-headertext="Create Date" e-textalign="left"></div>
            <div e-column e-field="MachineName" e-headertext="Machine" e-textalign="center"></div>
            <div e-column e-field="MessageTitle" e-headertext="Title" e-textalign="left"></div>
            <div e-column e-field="MessageBody" e-headertext="Message" e-textalign="left"></div>
            <div e-column e-field="Severity" e-headertext="Severity" e-textalign="left"></div>
            <div e-column e-field="UserID" e-headertext="User ID" e-textalign="left"></div>
        </div>
    </div>
</div>

--> WebAPI Method Call
[HttpPost]
        public IHttpActionResult GetLogs(LogQueryModel model)
        {
            if (model.IsNull())
            {
                return BadRequest();
            }

            InitializeSearchFields(model);

            var queryDto = queryTranslator.Translate(model);
            var logResults = resultTranslator.Translate(this.serviceClient.Client.GetLogs(queryDto));
            var logIndex = new LogIndexModel
            {
                LogQuery = model,
                LogResult = logResults
            };
            return Ok(logIndex);
        }


Could you please help? I looked through the forums and tried to find a similar scenario and was unable to. Any help would be much appreciated.

1 Reply

PK Prasanna Kumar Viswanathan Syncfusion Team June 17, 2015 12:50 PM UTC

Hi Mario,

Thanks for using Syncfusion Products.

We analyzed your query and we created a sample in Web API using Custom Service data in Angular Grid . While using custom service data we have initialize an empty data in the controller. For server side searching, we achieved using by sending dynamic url to the controller.

We performed searching operation using OdataQueryOptions. ODataQueryOptions parameter in server side controller which contains all the required parameters for  performing server side operations such as paging, sorting, searching and filtering

In OnComplete method, we have maintained the current state of the searching in Grid because of the dataSource changes will be cleared the grid current state. Once the angular $apply cycle is completed we have stored the current state of searching operation to the Grid.

Please refer the following code snippet :

<div ng-app="employeeView">

    <div ng-controller="GridCtrl">

        OrderID : <input type="text" ng-model="logQuery.OrderID" class="textbox" />

        <button ej-button e-field-size="large" e-field-showroundedcorner="true" ng-click="Search()">Search</button>

        <div ej-grid id="Grid" e-width="500px" e-datasource="data" e-allowsorting="true" e-allowPaging="true" e-toolbarsettings-showtoolbar="true" e-toolbarsettings-toolbaritems="tools">

            <div e-columns>

                <div e-column e-field="OrderID" e-headertext="Order ID" e-isprimarykey="true" e-textalign="right"></div>

                <div e-column e-field="CustomerID" e-headertext="Customer ID" e-textalign="right"></div>

                <div e-column e-field="EmployeeID" e-headertext="Employee ID" e-textalign="right"></div>

                <div e-column e-field="Freight" e-headertext="Freight" e-textalign="right"></div>

            </div>

        </div>

    </div>

</div>


<script>

    angular.module('custModule', []).factory("custService", ["$http", function ($http) {


        return {

            get: function () {

                return $http.get("/api/Orders/?", { cache: true });

            },

            search: function (value) {


              return $http.get("/api/Orders/?$inlinecount=allpages&$filter=(substringof(" + "'" + value + "'" + " ,tolower(OrderID))) or (substringof(" + "'" + value + "'" + ",tolower(CustomerID))) or (substringof(" + "'" + value + "'" + ",tolower(Freight))) or (substringof(" + "'" + value + "'" + ",tolower(ShipCountry)))")

            }

        };

    }]);


    angular.module('employeeView', ['ejangular','custModule'])

        .controller('GridCtrl', function ($scope, custService) {


            $scope.tools = ["add", "edit", "delete", "update", "cancel"];


            $scope.Search = function () {

                var grid = $("#Grid").ejGrid("instance");

                var scope = angular.element($("#Grid")).scope();

                custService.search(scope.logQuery.OrderID).then(onComplete);                    

            }


            $scope.data = [];

           

            custService.get().then(


                             function (response) {


                                 $scope.data = response.data.Items;

                             }

                        )


            function onComplete(response) {

               

                $scope.data = response.data.Items;

               

            }

        });

</script>
------------------------------------------------------------------------------------------------------------------------------------

public PageResult<OrdersView> Get(ODataQueryOptions opts)

        {

            var results = db.OrdersViews.AsQueryable();

            var count = results.Count();

            if (opts.OrderBy != null)

                results = opts.OrderBy.ApplyTo(results);

            if (opts.Filter != null)

            {

                if (opts.Filter.RawValue.Contains("substring"))

                {

                    string key = opts.Filter.RawValue.Split(new string[] { "'" }, StringSplitOptions.None)[1];

                    results = results.Where(fil => fil.CustomerID.Contains(key) || fil.EmployeeID.ToString().Contains(key) || fil.Freight.ToString().Contains(key) || fil.OrderID.ToString().Contains(key));

                }

                else

                    results = opts.Filter.ApplyTo(results, new ODataQuerySettings()).Cast<OrdersView>();

            }

            if (opts.InlineCount != null)

                count = results.Count();

            var data = results;

            //var count = emp.Count;

            //if (opts.Filter != null)

            //    count = data.Cast<OrdersView>().ToList().Count;


            return new PageResult<OrdersView>(results, null, count);
        }


For your convenience we have created a sample and same can be downloaded from the below link

Sample Link : http://www.syncfusion.com/downloads/support/forum/119401/ze/ServerOperations1317383374

If we misunderstood your query, please get back to us, we will be happy to assist you.

Please let me know if you need any further assistance.

Regards,
Prasanna Kumar N.S.V

Loader.
Live Chat Icon For mobile
Up arrow icon