简体   繁体   中英

Using JavaScript objects with angularjs $scope and share them between controllers

I'm starting with angularjs and I would like some tips about using JavaScript objects with $scope. Considering reuse my objects, I did the following:

function ObjectA() {
   this.prop1 = null;
   this.prop2 = null;
}

function ObjectB() {
   this.prop1 = null;
   this.prop2 = null;
   this.prop3 = new ObjectA();
}

And in may angularjs controller:

$scope.myObject = new ObjectB();

In this way I can use my objects in many controllers, without rewrite the following code in each one:

Controller 1:

$scope.myObject = {prop1: null, prop2: null, prop3: {...}}

Controller 2:

$scope.myObject = ...

This is a right way to do the things? In many tutorials I just see the literal way to instantiate objects in $scope.

Actually use a service to share data between controllers.

Example: http://jsfiddle.net/s2L4y82c/2/

<div ng-app='demo'>

    <div ng-controller='controller1 as ctrl1'>
        <h2>Controller 1</h2>
        <span>Prop1</span>
        <input type='text' ng-model='ctrl1.sharedService.prop1' />
    </div>
    <br>
        <hr>

     <div ng-controller='controller2 as ctrl2'>
         <h2>Controller 2</h2>
         <span>Prop1</span>
         <span>{{ctrl2.sharedService.prop1}}</span>
    </div>

</div>

And the JS part:

angular.module('demo', [])
.controller('controller1', [ 'sharedService', Controller1])
.controller('controller2', [ 'sharedService', Controller2])
.service('sharedService', SharedService);

function Controller1( sharedService){
    this.sharedService = sharedService;
}

function Controller2( sharedService){
    this.sharedService = sharedService;
}


function SharedService(){
    this.prop1 = null;
   this.prop2 = null;
   this.prop3 = new ObjectA();
}

function ObjectA() {
   this.prop1 = null;
   this.prop2 = null;
}

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