您的位置:首页技术文章
文章详情页

angular.js - angularjs在两个controller之间传值,使用factory,为何不成功?

【字号: 日期:2024-10-04 13:33:52浏览:66作者:猪猪

问题描述

希望通过服务在两个controller传值,代码如下:

angular.js - angularjs在两个controller之间传值,使用factory,为何不成功?但是并没有成功。。。

angular.js - angularjs在两个controller之间传值,使用factory,为何不成功?这单括号是什么鬼?

angular.js - angularjs在两个controller之间传值,使用factory,为何不成功?控制台只能得到setter 却没有getter请问这是为什么

问题解答

回答1:

1、那个单括号不是什么鬼,那是一个空对象。因为你在服务里面设置了myData为{},而且,你的getCtrl这个controller一开始就去获取了这个值,所以说在页面上会显示{};

2、在你点击add按钮的时候,其实已经把input里面的值存入了myData中,只是你的getCtrl不会去获取而已,简单一点,你可以在getCtrl中也设置一个按钮来点击获取myData的值;

3、在你的_getter函数中,你的这一句console.log..放在了return语句后面,无论怎么执行,都不会有输出的。

我按照你的代码稍微加了一点修改,你可以看看。

<p ng-app='myApp'> <p ng-controller='inputCtrl'><input type='text' ng-model='value' /><button ng-click='setValue()'>Add</button> </p> <p ng-controller='getCtrl'><p>{{ value }}</p><button ng-click='getValue()'>Get</button> </p></p>

angular.module(’myApp’, []) .factory(’factory_getValue’, function () {var myData = {};function _getter() { console.log(myData); return myData;}function _setter( a ) { myData = a;}return { getter: _getter, setter: _setter}; }) .controller(’inputCtrl’, function ( $scope, factory_getValue ) {$scope.setValue = function () { factory_getValue.setter($scope.value);} }) .controller(’getCtrl’, function ( $scope, factory_getValue ) {$scope.getValue = function () { // 点击按钮获取myData的值 $scope.value = factory_getValue.getter();} });