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

后端 未结 2 730
慢半拍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.

    0 讨论(0)
  • 2020-12-01 02:42

    Simply put shared data in the root scope, you'll be able to use them everywhere. In Angular $rootScope is the root of all scopes and can be used in controllers to manage data that must be visible across all modules. To use it just inject it in the controller function. For a detailed explanation refer to the Angular developer's guide and to the API doc.

    0 讨论(0)
提交回复
热议问题