简体   繁体   中英

Call controller function from outside

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM