Using the same controller on different elements to refer to the same object

后端 未结 2 740
慢半拍i
慢半拍i 2020-12-01 01:41

I figured if I slapped ng-controller=\"GeneralInfoCtrl\" on multiple elements in my DOM they would share the same $scope (or least two-way binding

2条回答
  •  攒了一身酷
    2020-12-01 02:28

    Each time the Angular compiler finds ng-controller in the HTML, a new scope is created. (If you use ng-view, each time you go to a different route, a new scope is created too.)

    If you need to share data between controllers, normally a service is your best option. Put the shared data into the service, and inject the service into the controller:

    function GeneralInfoCtrl($scope, MyService) {
    

    Each scope/controller instance will then be able to access the shared data.

    Note that services are singletons, so there will only be one instance of your shared data around.

    Here is a fiddle (I didn't write it) showing how two controllers can share data.

    See also AngularJS: How can I pass variables between controllers? and
    Angularjs: two way data bindings and controller reload.

提交回复
热议问题