Set Scope Variable from Separate Controller
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<div ng-app="myApp" class="app-wrapper">
<div ng-controller="Ctrl_1" class="ctrl1">
<h3>myVar = '{{ myVar }}'</h3>
<button ng-click="testFunction()">Set myVar equal to 'Bar'</button>
<ul class="console" style="list-style-type: none; padding: 0;">
<li ng-repeat="item in myList">{{ item }}</li>
</ul>
</div>
</div>
JavaScript
var app = angular.module('myApp', [])
.controller('Ctrl_1', function( $scope )
{
$scope.myList = ['item1','item2'];
$scope.myFunction = function( myParam, myList )
{
//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.myList = myList;
console.log('Ctrl_1: ' + $scope.myVar );
console.log('Ctrl_1: ' + $scope.myList );
}
$scope.myFunction('Foo', $scope.myList);
});
// sim.js
$('.app-wrapper').attr('ng-controller', 'Ctrl_2');
app.controller('Ctrl_2', function( $scope, $controller, $timeout, $compile, $document )
{
var Ctrl_1_ViewModel = $scope.$new();
$controller('Ctrl_1', { $scope: Ctrl_1_ViewModel } );
$compile($document.find('h3'))(Ctrl_1_ViewModel);
var template = '<li ng-repeat="item in myList">{{ item }}</li>';
var element = $document.find('.console').html(template);
$compile(element)(Ctrl_1_ViewModel);
//$timeout( function() { Ctrl_1_ViewModel.myFunction('Bar') } );
$scope.testFunction = function()
{
var myList = ['item3','item4'];
Ctrl_1_ViewModel.myFunction('Bar', myList);
console.log('Ctrl_2: ' + Ctrl_1_ViewModel.myVar );
}
});