angular.js - angularjs在兩個controller之間傳值,使用factory,為何不成功?
問題描述
希望通過服務在兩個controller傳值,代碼如下:
但是并沒有成功。。。
這單括號是什么鬼?
控制臺只能得到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();} });
