gpt4 book ai didi

javascript - 将对象返回给 Controller 并使用 AngularJS 打印属性值

转载 作者:行者123 更新时间:2023-11-30 00:05:22 26 4
gpt4 key购买 nike

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

工厂不能返回原始变量,对吗?所以我声明了一个对象。问题是 getList() 不能返回对象属性 data.product,它总是一个空字符串。

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

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

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

}

最佳答案

试试这个方法:

请点击此处: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();

}

关于javascript - 将对象返回给 Controller 并使用 AngularJS 打印属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38738682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com