首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将值从服务绑定到html -如何观察angular.js中组件的变化

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

Stack Overflow用户
提问于 2018-07-27 06:31:51
回答 1查看 194关注 0票数 1

如何绑定到来自服务的html值(来自服务的值是动态变化的,但我的组件没有观察到它)。我只想在我的组件html中像文本一样显示这个变量。

如下所示:

service.js

代码语言:javascript
复制
app.service('testService', function() {
    this.testData = {
        test1: 12,
        test2: 13
    }

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

component.js

代码语言:javascript
复制
(function() {

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

            controller: function(testService) {

             this.data = testService.testData;

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

})();

html

代码语言:javascript
复制
<button ng-click="vm.newFunction()">Click</button>

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

我该怎么处理呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-27 07:17:02

使用angular.copy

代码语言:javascript
复制
app.service('testService', function() {
    this.testData = {
        test1: 12,
        test2: 13
    }

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

演示

代码语言:javascript
复制
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;
    }
})
代码语言:javascript
复制
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
    <test-component></test-component>
</body>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51548361

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档