8664

Using a promise for retrieving data inside angular directive

Question:

I am working on hiding or showing elements based on user role from an api. The directive works when I set the data.roleName in the code but when I try to set it by I service I need to resolve a promise before loading the rest of the directive though I keep getting "cannot read property of undefined errors Here's the code.

<b>.js</b>

app.directive('restrictTo', ['SecuritySvc', function (SecuritySvc) { return { restrict: 'EA', replace: true, transclude: true, scope: {}, controller: ['$scope', '$attrs', '$q', 'SecuritySvc', function ($scope, $attrs, $q, SecuritySvc) { var defer = $q.defer(); defer.promise.then(function ($scope, SecuritySvc) { $scope.data = SecuritySvc.getRole(); }); defer.resolve(); if ($scope.data.roleName == $attrs.restrictTo) { $scope.allowed = true; } else { $scope.allowed = false; } console.log($scope.data); }], template: '<div ng-show="{{ $scope.allowed }}" ng-transclude></div>' } }]);

<b>.html</b>

<div restrict-to="customer"> <div class="hero-unit">

Welcome!

Hello, valued customer

</div> </div> <div restrict-to="Admin"> <div class="hero-unit">

Admin Tools

This shouldn't be visible right now

</div> </div>

Answer1:

If you dont want to use Q/defer and are using $resource you can do it this way:

app.directive('restrictTo', ['SecuritySvc', function (SecuritySvc) { return { restrict: 'AE', replace: true, transclude: true, scope: {}, controller: ['$scope', '$attrs', 'SecuritySvc', function ($scope, $attrs, SecuritySvc) { $scope.allowed = false; SecuritySvc.getMyRole().$promise.then(function (data,attrs) { if (data.roleName == $attrs.restrictTo) { $scope.allowed = true; } else { $scope.allowed = false; } }); }], template: '<div ng-show="allowed" ng-transclude></div>' };

}]);

Answer2:

Not sure what your SecuritySvc is or returns. I think you should do it in a way like this:

var defer = $q.defer(); defer.resolve(SecuritySvc.getRole()); defer.promise.then(function (data) { $scope.data = data; if ($scope.data.roleName == $attrs.restrictTo) { $scope.allowed = true; } else { $scope.allowed = false; } console.log($scope.data); });

Recommend

  • angularjs - using 'string' names on the scope or ng-model
  • How to setup the “Loading Data from a Server” example on the EmberJS homepage within an Ember CLI st
  • Socket.io emit to specific client in tabs
  • ExpressJS / NodeJS Redirect Image
  • How to focus on a particular portion of an another html page when click on a button or link
  • Display informations about a bubble chart D3.js in AngularJS
  • Property 'catch' does not exist on type 'PromiseLike
  • Handle Authentication and Authorization in jax-rs webservice with cxf
  • Compiling Element Causes Input Caret Position to Move to End
  • Optional spaces and multiple alternatives in wl-pprint-extras
  • I have a modal that opens a second modal and cannot close the first modal if open then close the sec
  • Enterprise Architect - Cancel Connectors Bridges
  • Why is my req.body always empty on POST?
  • R h2o.glm - issue with max_active_predictors
  • Using $compile in a directive triggers AngularJS infinite digest error
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • How to use jQuery's $.post() method with async/await and typescript
  • Best way to dynamically load an xml configuration file into a Flex4/Flash movie at runtime?
  • Web.config system.webserver errors
  • Authentication in Play! and RestEasy
  • How to revert to previous XCode version?
  • jQuery ready not fired after rails link_to is clicked
  • Make VS2015 use angular-cli ng at build time in a .NET project
  • JQuery Internet Explorer and ajaxstop
  • Bad request using file_get_contents for PUT request in PHP
  • Database structure design with variable amounts of fields
  • How to delay loading a property with linq to sql external mapping?
  • Cannot connect to cassandra from Spark
  • How do I fake an specific browser client when using Java's Net library?
  • Accessing IRQ description array within a module and displaying action names
  • How to get a value (ex: baseURL) in every Karate feature?
  • Javascript Callbacks with Object constructor
  • Where to put my custom functions in Wordpress?
  • Numpy divide by zero. Why?
  • Matrix multiplication with MKL
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • SQL merge duplicate rows and join values that are different
  • LevelDB C iterator
  • Can't mass-assign protected attributes when import data from csv file
  • Checking variable from a different class in C#