angular.js - angularjs uses factory to transfer values ​​between two controllers, why is it unsuccessful?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-15 17:00:22
0
1
720

I hope to pass values ​​between two controllers through services. The code is as follows:


But it was not successful. . .


What the hell is this single bracket?


The console can only get setters but no getters
Excuse me why?

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

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