简体   繁体   English

从外部调用控制器功能

[英]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 ). 以这个为例( 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 http://jsfiddle.net/o2b0bdbr/您不在角度摘要循环之内,因此您需要让他知道他的示波器上发生了某些事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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