AngularJS use a global variable within a template for orderBy ng-repeat value

232 Views Asked by At

I'm working on a angular app which I do not have access to the source of the app only to the component html code. I want to re-order a array with a custom function, but I'm not sure it's possible to access global variables within the template.

This works and sorts the fields by the value of "name" property.

<div ng-repeat="$field in $fields | orderBy:'name' track by $field.name " >
   <input ng-model="$item[$field.name] " />
</div>

If I try this, this will not work

Not Work

<script>var orderByProperty = 'name'; </script>
<div ng-repeat="$field in $fields | orderBy:orderByProperty track by $field.name " >
   <input ng-model="$item[$field.name] " />
</div>

How can I access a global variables from within the angular template?

I do not have access to the controller code of the app or main js file of the app, only to the html of component. A solution how to order the array within the template will also solve this issue.

2

There are 2 best solutions below

1
Vishnu On

you can use ng-init to add some variables in html as:

<body ng-controller="MainCtrl as ctrl" ng-init="orderByProperty = 'name'">
    <div ng-repeat="$field in $fields | orderBy:orderByProperty track by $field.name ">
        <input ng-model="$field.name" />
    </div>        
</body>
0
georgeawg On

How can I access a global variables from within the angular[JS] template?

You can't.

From the Docs:

AngularJS expressions are like JavaScript expressions with the following differences:

  • Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object.

For more information, see