I'm using Angular for the UI for an embedded system. I have the app setup so that you can run the UI in a desktop browser (a simulation of the embedded system). I have a service layer that contains all the API functions for the embedded system. So for the simulation, I just swap out the service layer to simulate the API functions. This works well, but now my problem is that I need to actually do stuff in the simulation that is not part of the embedded system.
I do not want any code for the simulation in any of the controllers. I've successfully been able to get a controller for the simulation just by loading a single .js file and even call a function in a separate controller, but I can not change the value of a scope variable. It does not work as I would expect it to.
Here is a demo that demonstrates what happens. I'm calling a function in the first controller from the second controller and passing a parameter. The console prints out the correct value, but the scope variable doesn't change.
var app = angular.module('myApp', [])
.controller('Ctrl_1', function( $scope )
{
$scope.myFunction = function( myParam )
{
console.log('Ctrl_1: ' + myParam );
// Demonstrates that the function is called, and with the correct value for myParam.
$('.console').append('<li>' + myParam + '</li>');
$scope.myVar = myParam;
}
$scope.myFunction('Foo');
});
// sim.js
$('.app-wrapper').attr('ng-controller', 'Ctrl_2');
app.controller('Ctrl_2', function( $scope, $controller, $timeout )
{
var Ctrl_1_ViewModel = $scope.$new();
$controller('Ctrl_1', { $scope: Ctrl_1_ViewModel } );
//$timeout( function() { Ctrl_1_ViewModel.myFunction('Bar') } );
$scope.testFunction = function()
{
Ctrl_1_ViewModel.myFunction('Bar');
console.log('Ctrl_2: ' + Ctrl_1_ViewModel.myVar );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp" class="app-wrapper">
<div ng-controller="Ctrl_1">
<h3>myVar = '{{ myVar }}'</h3>
<button ng-click="testFunction()">Set myVar equal to 'Bar'</button>
</div>
<ul class="console" style="list-style-type: none; padding: 0;"></ul>
</div>
I also have a JSFiddle of the demo.
How can I get this to work? Or, is there a different approach I should consider?
$rootScopeas little as possible