0

I have a constant file which looks like this

demo.constant.js

// Add detail constans here
(function () {
    angular.module('myApp').constant('TYPE', {
        DYNAMIC: 'dynamic',
        STATIC: 'static'
    });
}());

Now I have a controller file that looks similar to this.

demo.controller.js

(function() {
    var DemoController = function(DEP1,DEP2, .... , TYPE)
    console.log(TYPE.DYNAMIC); // works perfectly
    var self = this;
    self.type = '';
    ...
    ...
    angular.module('myApp.controllers').controller('DemoController', DemoController);
})();

I am trying to access these constants in the HTML file like this:-

<div ng-controller="DemoController as self">
    <span ng-if="(self.type === 'dynamic')"> <!--instead of 'dynamic' I want to use TYPE.DYNAMIC-->
    ...
    ...
    ...
    </span>
</div>

Note:- {{self.type}} works but {{TYPE.DYNAMIC}} doesn't.

Another problem is that I want to use this constant as the value of radio buttons.

somewhat like this:-

<input type="radio" name="type" ng-model="self.inputType" value="dynamic"> <!-- Here I want to use TYPE.DYNAMIC -->
<input type="radio" name="type" ng-model="self.inputType" value="static">  <!-- Same as above -->

I have searched everywhere but nothing seems to work. Please Help!!

2 Answers 2

1

One approach is to assign the constant to a controller property:

function DemoController(DEP1,DEP2, /*.... ,*/ TYPE) {
    console.log(TYPE.DYNAMIC); // works perfectly

    this.TYPE = TYPE;
}
angular.module('myApp.controllers').controller('DemoController', DemoController) 

Then use it in the template:

<div ng-controller="DemoController as $ctrl">
    <span ng-if="$ctrl.type === $ctrl.TYPE.DYNAMIC">
    ...
    </span>
</div>

Note: The ng-if directive uses creates a child scope. Consider instead using the ng-show directive which uses CSS and less resources.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use $rootScope and initilize it in run phase:

angular.module('app')
  .run(function ($rootScope, TYPE) {
      $rootScope.TYPE = TYPE
   });

then you can use it directly in your HTML

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.