希望通过服务在两个controller传值,代码如下:
但是并没有成功。。。
这单括号是什么鬼?
控制台只能得到setter 却没有getter
请问这是为什么
曾经蜡笔没有小新2017-05-15 17:02:22
1. That single bracket is nothing, it is an empty object. Because you set it in the service myData
为{}
,而且,你的getCtrl
这个controller一开始就去获取了这个值,所以说在页面上会显示{}
;
2. The value when you click add
按钮的时候,其实已经把input里面的值存入了myData
中,只是你的getCtrl
不会去获取而已,简单一点,你可以在getCtrl
中也设置一个按钮来点击获取myData
;
3. After your _getter
函数中,你的这一句console.log..
放在了return
statement, no matter how you execute it, there will be no output.
I modified it slightly according to your code, you can take a look.
<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();
}
});