timbo timbo - 1 year ago 85
Javascript Question

Accessing 'as' controller property from external Javascript

I have Javscript mapping component which on addition to a map, I would like to get a color preference from an Angular 1.5 'as' controller which drives user preferences.

So may controller code looks like:

app.controller('PreferenceController', function($http, $httpParamSerializer) {

this.preferredBoundaryColorHex = '#007fff';

And in the html is:

<div ng-controller="PreferenceController as pref">
... preference html

How to I get a reference to the controller from outside Angular? My understanding is that the preference is just an object property on the controller.

Answer Source

Use angular.element

var pref = angular.element(jsReferenceToElement).controller();
var colour = pref.preferredBoundaryColorHex;

Where jsReferenceToElement is the return value from something like getElementById or querySelector.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download