angular.js - angularjs在兩個(gè)controller之間傳值,使用factory,為何不成功?
問題描述
希望通過服務(wù)在兩個(gè)controller傳值,代碼如下:
但是并沒有成功。。。
這單括號(hào)是什么鬼?
控制臺(tái)只能得到setter 卻沒有g(shù)etter請(qǐng)問這是為什么
問題解答
回答1:1、那個(gè)單括號(hào)不是什么鬼,那是一個(gè)空對(duì)象。因?yàn)槟阍诜?wù)里面設(shè)置了myData為{},而且,你的getCtrl這個(gè)controller一開始就去獲取了這個(gè)值,所以說在頁面上會(huì)顯示{};
2、在你點(diǎn)擊add按鈕的時(shí)候,其實(shí)已經(jīng)把input里面的值存入了myData中,只是你的getCtrl不會(huì)去獲取而已,簡單一點(diǎn),你可以在getCtrl中也設(shè)置一個(gè)按鈕來點(diǎn)擊獲取myData的值;
3、在你的_getter函數(shù)中,你的這一句console.log..放在了return語句后面,無論怎么執(zhí)行,都不會(huì)有輸出的。
我按照你的代碼稍微加了一點(diǎn)修改,你可以看看。
<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 () { // 點(diǎn)擊按鈕獲取myData的值 $scope.value = factory_getValue.getter();} });
