Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access dynamic $scope variable inside html

I'm creating a large amount of directives and all will include dynamic scope variables that will be initialised inside the link functions e.g:

//
link: function(scope, ele, attr){
  scope.key = scope.somevar + 'something_else';
  scope[scope.key] = 'the_value';
}
//

I want to access the value in the templates of the directives viascope.key.

<div ng-if="scope[key]"> something </div>

Currently I only see it been viable through a function call like so:

html

<div ng-if="scope(key)"> something </div>

js

scope.scope = function(key) {
  return scope[key];
}

But then the problem is I will need to copy this into all the directives.

Another option I considered was to assign the getter function onto the $rootScope making it globally accessible but how do I bind it to or pass in the current directives scope. (If even possible).

What would be a good approach to this?

like image 611
Kiee Avatar asked Dec 22 '15 13:12

Kiee


2 Answers

Inside of Angular template this keyword points to the current evaluation context, i.e. current scope. It means that you would be able to achieve what you are after by using bracket notation on the this object:

<div ng-if="this[key]"> something </div>
like image 127
dfsq Avatar answered Nov 14 '22 17:11

dfsq


Use bindToController option in your directive

JS

bindToController: true,
controller: 'MyController',
controllerAs: 'ctrl',
link: function(scope, ele, attr){
  scope.ctrl.key = scope.somevar + 'something_else';
  scope.ctrl[scope.ctrl.key] = 'the_value';
}

HTML

<div ng-if="ctrl[ctrl.key]"> something </div>

Check this codepen as example: http://goo.gl/SMq2Cx

like image 43
Gonzalo Pincheira Arancibia Avatar answered Nov 14 '22 18:11

Gonzalo Pincheira Arancibia