Is there a way to access an array that I have on my controller and accurately render it in my <script> tags on my jade template.
For example:
Controller.js
$scope.myArray = ["item1","item2"];
On my index.jade:
script.
var clientArray = {{myArray}}
I have so far not been successful so I am wondering if this is a possibility with Jade+Angular.
Any help would be greatly appreciated.
Update - Error returned when using the above config
SyntaxError: Unexpected token {
at eval (native)
You cannot directly access scope objects in your script. scope is assigned to an element during angular rendering of that entity (controller, directives etc). You need to get hold of the element that holds the scope and get the item from the scope by calling .scope() on the element, and do it only when the element is ready.
Example:-
Say your controller is:-
app.controller('MainCtrl', function($scope) {
$scope.myArray = ["item1","item2"];
});
and you have this controller in your markup.
<div class="ctrl" ng-controller="MainCtrl">
<!-- ....some content -->
</div>
Then you can access by doing:-
<script>
angular.element(document).ready(function() { //Or get an instance of $timeout from the injector
var clientArray = angular.element('.ctrl').scope().myArray;
console.log(clientArray);
});
//Or run it via the timeout which is pushed into the async queue and is run after angular has manipulated the DOM again it is relative.
var timeout= angular.injector(['ng']).get('$timeout');
timeout(function(){
var clientArray = angular.element('.ctrl').scope().myArray;
console.log(clientArray);
});
</script>
There are many caveats here:-
1) You need to make sure when your script is run the angular must have already assigned the scope to the element. (Basically angular has done its DOM rendering)
2) You need to select the specific element which has the scope attached.
In the previous example the selector worked because i have jquery loaded before angular. otherwise you would have to access the element using native DOM methods, example
angular.element(document.querySelector('.ctrl')).scope().myArray
But regardless, you should try not to get into a position to access the scope objects outside angular. If you point out what your specific issue is there could be a better way to handle it.