cdz cdz - 4 months ago 6
AngularJS Question

Return object to controller and print property value with AngularJS

I've created a simple app that share data between controllers. A button increment a variable number value in a controller (A) and then it shares data with other controller (B)

Factory can't return primitives variables, right? So I declared an object. The problem is that getList() can't return the object property data.product, it is always an empty string.

When I return the full object, it works fine. scope.total in ControllerB is {"product":x}

What would be the best way to achieve this? I only need to share the variable scope.total from one controller to the other one, not the full object.

HTML

<div ng-app="tabsApp">

<div id="London" class="tabcontent">
<div ng-controller="tabOneController as vm">
<input type="button" value="add" ng-click="vm.addMore()"/>
</div>
</div>


<div id="Paris" class="tabcontent">
<div ng-controller="tabTwoController as vm">
<span>{{vm.total}}</span>
</div>
</div>

</div>


JS

angular
var app = angular.module('tabsApp', []);
app.controller("tabOneController", controllerA);
app.controller("tabTwoController", controllerB);
app.factory('myData', function() {

var data = {
product: ''
};


function addItem(value) {
data.product = value;
}

function getList() {
return data;
}

return {
addItem: addItem,
getList: getList
};

});


function controllerA(myData){

var scope = this;
scope.total = 0;

scope.addMore = function(){
scope.total++;
myData.addItem(scope.total);
}

}

function controllerB(myData){

var scope = this;
scope.total = myData.getList();

}

Answer

try this way:

plnkr here: https://plnkr.co/edit/Bpf1RSKhsRr92Qi7168q?p=preview

<div ng-app="tabsApp">

  <div id="London" class="tabcontent">
        <div ng-controller="tabOneController as vm">
        <input type="button" value="add" ng-click="vm.addMore()"/>
        </div>
  </div>


  <div id="Paris" class="tabcontent">
      <div ng-controller="tabTwoController as vm">
          <span>{{vm.total.product}}</span>
      </div>
  </div>

</div>

then inside the .js

var app = angular.module('tabsApp', []);
  app.controller("tabOneController", controllerA);
  app.controller("tabTwoController", controllerB);
  app.service('myData', function() {

      var data = {
        product: 0
      };

      this.addItem = function (value) {
        data.product = value;
      }

      this.getList = function() {
        return data;
      }

    });



function controllerA(myData){

  var scope = this;
  scope.total = 0;

  scope.addMore = function(){
    scope.total++;
    myData.addItem(scope.total);
  }
}

function controllerB(myData, $scope){

  this.total = myData.getList();

}
Comments