【问题标题】:Bind value from service to html - how to observe change by component in angular.js将值从服务绑定到 html - 如何在 angular.js 中观察组件的变化
【发布时间】:2019-01-04 00:17:29
【问题描述】:

如何绑定到来自服务的 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>

所以,如果我点击按钮,我想要 data = {test1: 22, test2: 23},但我仍然有 data = {test1: 12, test2: 13}

我该如何处理?

【问题讨论】:

    标签: angularjs components


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 2021-05-04
      • 2015-11-06
      相关资源
      最近更新 更多