Search code examples
javascriptc#htmlangularjscefsharp

Passing data from C# to angular js html


I'm building a application using CefSharp which only shows a webpage. I just want to know how do we pass data from my C# app (using CefSharp) to a html which contain a angularjs controller?

For example, if my data are hardcoded, it will be like below:

MainController.js:

app.controller('MainController', ['$scope', function($scope) { 
 $scope.qnumbers = [  // hardcoded data
  {
      counter : 'A',
      number : '3456'
  },
  {
      counter : 'B',
      number : '1234'
  },
  {
      counter : 'C',
      number : '7890'
  },
  {
      counter : 'D',
      number : '1122'
  },
  {
      counter : 'E',
      number : '6677'
  },
  {
      counter : 'F',
      number : '5656'
  },
 ]; 
  }]);

Then my html would be something like this:

                <div class="reg" ng-repeat="qnumber in qnumbers">
                   div class="u1">{{qnumber.counter}}</div>
                   <div class="u2">{{qnumber.number}}</div>
                </div>

What if now my data is not hardcoded but comes from my C# application, how would I have to write in my html? How do we pass the data into the MainController?


Solution

  • Check out this documentation How do you call a Javascript method from .NET?

    You can do anything you want if you successfully use this. For example, set up a $scope.$watch on one global variable, let's say qnumber.updated and then update $scope.qnumbers with data passed by your C# code once the watch gets triggered.

    Note that you will have to manually trigger a digest process after you change the global variable outside of angular.

    Example:

    angular.module('app', [])
      .controller('Main', function($scope) {
        $scope.$watch(function() {
          return window.qnumbers;
        }, function(data) {
          $scope.qnumbers = window.qnumbers || 'default';
        });
      });
    

    You can execute the following command to fire this watch.

    window.qnumbers = [1,2,3];
    angular.element(document.getElementById('ctrl')).scope().$apply();
    // ctrl is the id of you controller container
    

    Check out this link as an example, and try to execute the command above in the console. You can do the same within your EvaluateScriptAsync method http://codepen.io/anon/pen/wGzXKv