将值从服务绑定到html-如何观察angular.js中组件的变化

时间:2018-07-26 22:31:51

标签: angularjs components

如何绑定到服务中的html值(服务中的值是动态变化的,但是我的组件未观察到它)。我只想在组件html中将此变量显示为文本。

类似的东西:

service.js

app.service('testService', function() {
    this.testData = {
        test1: 12,
        test2: 13
    }

    this.newFunction() {
        this.testData = {
          test1: 22,
          test2: 23
    }
});

component.js

(function() {

    angular.module('test.module')
        .component('testComponent', {
            templateUrl: '/test.html',
            controllerAs: 'vm',

            controller: function(testService) {

             this.data = testService.testData;

             this.nextPage = () => {
                 this.newFunction();
             }
         }
    });

})();

html

<button ng-click="vm.newFunction()">Click</button>

因此,如果我单击按钮,我希望有数据= {test1:22,test2:23},但我仍然有data = {test1:12,test2:13}

我该如何处理?

1 个答案:

答案 0 :(得分:1)

使用angular.copy

app.service('testService', function() {
    this.testData = {
        test1: 12,
        test2: 13
    }

    this.newFunction = () => {
        var newData = {
          test1: 22,
          test2: 23
        };
        angular.copy(newData, this.testData);
    }
});

演示

angular.module("app",[])
.service('testService', function() {
    this.testData = {
        test1: 12,
        test2: 13
    }
    this.newFunction = () => {
        var newData = {
          test1: (Math.random()*100).toFixed(0),
          test2: (Math.random()*100).toFixed(0)
        };
        angular.copy(newData, this.testData);
    }
})
.component('testComponent', {
    template: `
      <div>
        <pre>
   test1={{vm.data.test1}}
   test2={{vm.data.test2}}
        </pre>
        <button ng-click="vm.nextPage()">Next Page</button>
      </div>
    `,
    controllerAs: 'vm',
    controller: function(testService) {
      this.data = testService.testData;
      this.nextPage = testService.newFunction;
    }
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
    <test-component></test-component>
</body>