使用AngularJS将对象返回到控制器并打印属性值

时间:2016-08-03 08:45:06

标签: javascript angularjs

我创建了一个在控制器之间共享数据的简单应用。按钮在控制器(A)中递增可变数值,然后与其他控制器(B)共享数据

工厂无法返回原语变量,对吧?所以我宣布了一个对象。问题是getList()无法返回对象属性data.product,它总是一个空字符串。

当我返回完整的对象时,它工作正常。 ControllerB中的scope.total是{“product”:x}

实现这一目标的最佳方法是什么?我只需要将变量scope.total从一个控制器共享到另一个控制器,而不是完整的对象。

HTML

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();

}

JS

Host.Local.FindSingle("//button[@automationid='autoidname']");

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

plnkr: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>

然后在.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();

}