Reputation: 2098
I need to access (call and/or modify) the scope of a controller from outside of it.
Following this answer I managed to access the scope, but the data binding doesn't kick in...
Take this as example (JSFiddle).
angular.module("App", []).controller("Test", function($scope)
{
$scope.list = ["added on initialization"];
$scope.add = function(item)
{
$scope.list.push(item);
};
});
var addFromOutside = function()
{
angular
.element(document.getElementById("TestController"))
.scope()
.add('added from outside');
};
<div ng-app="App" ng-controller="Test" id="TestController">
<ul>
<li ng-repeat="item in list track by $index">
{{item}}
</li>
</ul>
<button ng-click="add('added from inside')">Add from inside</button>
</div>
<button onclick="addFromOutside()">Add from outside</button>
If you click in the "Add from inside" button it works like expected.
But if you click in the "Add from outside" button nothing happens until you click in the "Add from inside" button...
Is there anyway to do this and the have data binding working?
Upvotes: 1
Views: 990
Reputation: 5435
you forgot to add
scope.$apply()
http://jsfiddle.net/o2b0bdbr/ you are outside of angulars digest cycle so you need to let him know that something happen to on of his scopes
Upvotes: 2