1

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?

3
  • why do you want to call it from outside? I mean you can use ng-controller multiple times if you need to Commented Feb 19, 2015 at 19:20
  • yeah, just wrap that button with <div ng-controller="Test"></div> Commented Feb 19, 2015 at 19:30
  • @JohnyStark, saddly, a controller isn't a singleton... This means that each call to ng-controller creates another instance of it, so, the properties aren't shared between instances. =/ Commented Feb 19, 2015 at 20:04

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Simple and effective... Thanks.
I have to wait a couple of minutes to accept it, but I will... =]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.