Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access local sails variable in angular

I am passing in two variables to my view. How can I access this variable from an angular controller?

Sails Controller:

return res.view('dashboard', {
    me: {
      id: user.id,
      apiKey: user.connection.apiKey
    }
 });

Angular Controller:

angular.module('DashboardModule').controller('DashboardController', function($scope, $http) {
  $http.get("/api/" + encodeURIComponent($scope.me.apiKey));
  .success(function(response) {$scope.records = response.records;});
  }
});

HTML:

<h5>Api Key:</h5>
  <p ng-model="me.apiKey"><%= me.apiKey %></p>

  <ul>
    <li ng-repeat="x in records">
      {{ x.guiLoginName }}
    </li>
  </ul>

As you can see I am trying to perform a GET to a specific apiKey which is a variable. This variable is accessible from EJS but not angular. What am I doing wrong? To be fair, I fundamentally don't understand how sails communicates with angular...

like image 921
CiscoKidx Avatar asked Jan 18 '26 04:01

CiscoKidx


1 Answers

Sails doesn't communicate with Angular, as simple as that. Sails is front-end agnostic.

You can render your locals variables to your template because there's a template pass when you call res.view() but that basically sets your <%= me.apiKey %> block.

What you could do is:

  • make the variables available in the location, and get them through the route params (look up ui-router).
  • pass it via the window object of the browser:

In your template:

<script>
    var apiKey = <%= me.apiKey %>;
</script>

and then in Angular you could recover them as:

app.controller('DashboardController', ['$scope', '$window',
    function ($scope, $window) {
        $scope.apiKey = $window.apiKey;
    }
]);
like image 131
fixmycode Avatar answered Jan 20 '26 20:01

fixmycode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!