weixin_33724659 2016-09-14 14:51 采纳率: 0%
浏览 5

角Ajax服务

I want a service which can share/auto sync data to 2 or more controllers like this example:

app.js (from example)

var myApp = angular.module('myApp', []);


myApp.factory('Data', function(){
return { FirstName: '' };
});

myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.Data = Data;
});

myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.Data = Data;
});

jsFiddle example

Furthermore I need to load the data with ajax. I tried a bit but for ajax I need the promise (so the controller dont get changed data after init) which dont worked with the shared object like the fiddle link. If possible I want a solution without events (rootscope broadcast).

How can i use both techniques together? Do you guys know what I mean? :)

  • 写回答

2条回答 默认 最新

  • weixin_33736048 2016-09-14 15:05
    关注

    Change your service to like this:

    myApp.factory('Data', function(){
        this.name= { FirstName: '' };
        return this;
    });
    

    Controllers:

    myApp.controller('FirstCtrl', function( $scope, Data ){
        $scope.Data = Data.name;
    });
    
    myApp.controller('SecondCtrl', function( $scope, Data ){
        $scope.Data = Data.name;
    });
    
    评论

报告相同问题?