Angular.js:如何将数据从一个HTML更新到使用相同控制器的另一个HTML

Angular.js: How to update data from one HTML to other HTML which uses same controller

本文关键字:HTML 更新 另一个 控制器 一个 js 数据 Angular      更新时间:2023-09-26

我有以下 2 个 html 页面

1. 首页.html

<div data-ng-controller="userComments">
         <Will display all the comments>
</div>

2. 评论.html

<div data-ng-controller="userComments">
         <Have a comment box and submit button. 
         Submit button calls submit() function on ng-click>
</div>

其中comments.html是从主页启动的弹出窗口。和控制器

    .controller('userComment',['$scope', function($scope){
        $scope.title = 'User Comment';
        $scope.comments = <db call>
        $scope.cmt = '';
        $scope.submit = function(){
            console.log("comment just entered", $scope.cmt);
            $scope.comments = $scope.comments.concat($scope.cmt);
            console.log("Updated Comments", $scope.comments);
            };
    }])

新注释也需要在home.html中自动更新。我应该怎么做才能做到这一点?

谢谢

更新:

当评论添加到comment.html页面时,ng-click触发submit功能,$scope.comments会使用新评论进行更新,但是我应该怎么做才能在home.html中获取更新的评论?

在不同视图上使用相同的控制器时,将创建控制器的不同实例。您需要一个工厂或服务来存储和共享数据视图。

所以在你的情况下,你会需要一个注释工厂,比如

myApp.factory('commentsService', function() {
  return {
    comments: []
  };
});

然后在控制器中:

.controller('userComment',['$scope', 'commentsService', function($scope, commentsService){
    $scope.title = 'User Comment';
    $scope.comments = commentsService.comments;
    $scope.cmt = '';
    $scope.submit = function(){
        console.log("comment just entered", $scope.cmt);
        $scope.comments = $scope.comments.concat($scope.cmt);
        // store the comments for use across views
        commentsService.comments = $scope.comments;
        console.log("Updated Comments", $scope.comments);
        };
}])

您可以构建注释服务来进行数据库调用,因为这是一个角度的最佳实践(不要从控制器获取外部数据,而是从工厂/服务中获取)。您将构建一个名为getComments()之类的方法,然后从控制器调用它。

看:https://docs.angularjs.org/guide/services

Angularjs - 更新同一控制器的多个实例

Angularjs 提供双向绑定,因此插入

<div data-ng-controller="userComments">
         {{comments}}
</div>

会更新评论。要在整个应用程序中拥有相同的数据(由ng-app指令定义的数据),请定义一个服务

  • 您可以将服务注入任何控制器
  • 服务数据在整个应用程序中是相同的。

使用模块的服务方法创建服务。

var app = angular.module('myApp',[]).service('myService', function() { 
    this.comments = [];
    });

向控制器注入服务:

.controller('MyController',['myService',function(myService){
this.addComments = function(data){
myService.comments.push(data);
}
this.getComments = function(){
return myService.comments;
};
}]);

这将使数据在整个应用程序中保持相同,并且您还可以将此服务注入到另一个控制器。

调用使用服务的更高版本的控制器:

<div ng-controller="MyController as mc">
    {{mc.getComments()}}
</div>

在另一个视图中,设置:

<div ng-controller="MyController as mc">
    <input type="text" ng-model="myComm"/>
    <button type="submit" ng-click="mc.addComment(myComm)" value="Add comment"></button>
</div>

它使用新注释设置服务。 myComm 是可变的。ng-model 设置为输入文本,用户输入,并在用户单击时执行 ng-click 属性。

最后,有棱角的服务。网络调用有$http,$timeout特定时间后调用事物。您可以将它们用于特定操作,也可以拥有自己的服务。

您还可以使用 AngularJS 中捆绑的事件来传达这两个实例。因此,每次注释数组发生更改时,您都可以触发另一个控制器侦听的自定义事件,然后更新另一个控制器的注释数组。