angular.js - angularjs在两个controller之间传值,使用factory,为何不成功?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-15 17:00:22
0
1
658

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


但是并没有成功。。。


这单括号是什么鬼?


控制台只能得到setter 却没有getter
请问这是为什么

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(1)
曾经蜡笔没有小新

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();
        }
    });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!