search

Home  >  Q&A  >  body text

angular.js - angular在service下写的赋值在controller的$scope上监听不到?

比如赋值一个对象就无法双向绑定,而赋值成字符串什么的就可以被监听到。如果我必须赋值成对象怎么办才由办法让它能双向绑定(我说的时点击按钮后赋的值不能绑定)

<body ng-app="app">

    <p ng-controller="loginCtrl">
        <pre>{{info}}</pre>
        <button ng-click="setvalue()">aaaa</button>
    </p>
    <p ng-controller="loginCtrl">{{info.isIn}}</p>
    <script type="text/javascript">
    var app = angular.module('app', []);

    app.factory('login', ['$timeout', function($timeout){
        var ret = {}

        ret.info = {
            isIn:false
        }
        //如果这里赋值成这样
        var dd = {
            isIn:'aaaaa'
        }
        $timeout(function() {
            ret.info.isIn = true;
        }, 1000);
        ret.setvalue = function(){
            //这里的修改就无法绑定,这事为什么
            ret.info = dd
            //ret.info.isIn=dd.Isin  //这样写就可以
        }
        return ret;
    }]);

    app.controller('loginCtrl', ['$scope', 'login', function($scope, login){

        $scope.info = login.info;
        $scope.setvalue = function(){
            login.setvalue('dddd')
        }
    }])
    </script>
</body>

因为服务器上的数据就是一个jsonp对象,传下来有很多。
各位大大求救啊~~,上面的代码引入angular就能跑了,帮我改正改正

天蓬老师天蓬老师2743 days ago629

reply all(2)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-15 16:53:05

    <p ng-controller="loginCtrl">
        <pre>{{login.info}}</pre>
        <button ng-click="setvalue()">aaaa</button>
    </p>
    
    app.controller('loginCtrl', ['$scope', 'login', function($scope, login){
    
            $scope.login= login;
            $scope.setvalue = function(){
                login.setvalue('dddd')
            }
        }])
    

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-15 16:53:05

    This involves basic knowledge of js and has nothing to do with angular. Simple example:

    jsvar ret = {};
    ret.info = {isIn:false};
    var $scope = {};
    $scope.info = ret.info;
    
    //这里修改
    ret.info = {isIn:true,xx:'xx'};
    console.log(ret.info, $scope.info);// 结果是:Object {isIn: true, xx: "xx"} Object {isIn: false}
    

    reply
    0
  • Cancelreply