angular service讲解

controller是相对独立的,也就是说,两个controller之间,内存是不共享的,这个controller是无法访问其他其他controller的属性或者方法的;

以前,我都是通过localStorage来进行储存,后来发来localStorage应该是用来存储持久化数据,用来存储临时数据,controller互相交互,官方建议通过service来进行相互访问。
 
也就是说,service是用于不同controller或者directive中用于共享数据的一种服务
 
举例说明:
html
<!-- 一个controller -->
    <div style="background: yellow;" ng-controller="worldCtrl">
        {{author.name}}
        <br/> {{author.sex}}
        <button ng-click="update()">同步数据</button>
    </div>

    <!-- 另一个controller -->
    <div ng-controller="helloCtrl">
        {{author.name}}
        <br/> {{author.sex}}
        <button ng-click="updatePublic()">更新公有变量</button>
    </div>

controller.js

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

app.controller('worldCtrl', function($scope, demoService) {
    $scope.author = demoService.publicAuthor;
    
    $scope.update = function() { //同步数据
        $scope.author = demoService.publicAuthor;
    }
});

app.controller('helloCtrl', function($scope, demoService) {
    $scope.author = demoService.publicAuthor;

    $scope.updatePublic = function() { //更新您数据
        demoService.publicAuthor = {
            name: 'fei',
            sex: 'female'
        }
        $scope.author = demoService.publicAuthor;
    }
});

service.js

app.service('demoService', function () {
    var privateAuthor = {              //私有变量
        name: 'jack',
        sex: 'male'
    }

    this.publicAuthor = {        //共有变量
        name: 'rose',
        sex: 'female'
    }

    this.getPriAuthor = function () {          //获取私有变量
        return publicAuthor;
    }
});

end.

原文地址:https://www.cnblogs.com/91allan/p/5418308.html