Erick Engelhardt
Erick Engelhardt

Reputation: 734

Reusable string in angular app

In a application, some objects have icons. In PHP I would call

class Icons {
    const OBJECT_A_ICON = 'fa-icona';
    const OBJECT_B_ICON = 'fa-iconb';
    const OBJECT_C_ICON = 'fa-iconc';
}

echo Icons::OBJECT_C_ICON;

What is the best approach to do this in angular?

Upvotes: 1

Views: 131

Answers (4)

jad-panda
jad-panda

Reputation: 2547

Use constant service.

Constant Docs.

angular.module('app', [])
  .constant('ICON_CONSTANT', {
    Icon_A: 'fa-icona',
    Icon_B: 'fb-iconb',
    Icon_C: 'fc-iconc'
  })
  .controller('cntrl', function($scope, ICON_CONSTANT) {
      $scope.icon = ICON_CONSTANT.Icon_A;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="cntrl">
    {{ icon }}
  </div>
</div>

Upvotes: 1

errata
errata

Reputation: 26912

It sounds like you are looking for constants or immutable objects. There are no immutable objects in regular javascript or angular so you would probably want to use a standard $scope variable. MK's answer is pretty solid. This is kind of interesting: https://facebook.github.io/immutable-js/

Upvotes: 0

ccnokes
ccnokes

Reputation: 7115

angular.constant

https://docs.angularjs.org/api/auto/service/$provide#constant

It would look something like:

angular.module('app', [])
.constant('OBJECT_A_ICON', 'fa-icona');

Or you could put them all in one object.

Upvotes: 3

M K
M K

Reputation: 9416

Use a service:

angular.module('myApp').factory('icons', function(){
    return {
        icon_1: '',
        icon_2: ''
    };
})

.controller('myController', function(icons) {
    console.log(icons.icon_1);
});

Upvotes: 2

Related Questions