Home  >  Q&A  >  body text

angular.js - 请问angularjs里关于controller之间通信问题

我在做一个问答系统,其中有一个问题单页面,列出问题信息,然后列出问题下的回答列表。我给这个问题单页用了 QuestionCtrl 控制器,然后用http.get获取answers,用ng-repeat列出每个answer。然后每个answer我都用相同的控制器 AnswerCtrl来控制, 其中每个answer都有个赞的功能,一开始获取到answer时 ,我会把answer.prised_counter获取到显示,也就是回答当前被赞的数量。然后我给赞的元素a标签上加上ng-click去执行赞的操作,这时候调用的是AnswerCtrl里的function,赞了之后,我想要把answer.prised_counter+1,但是因为ansewr是从QuestionCtrl里的answers里读出来的,所以在AnserCtrl里我修改不了ansser.prised_counter这个变量。请问这个情况我应该怎么实现啊?是不是方案不对?

仅有的幸福仅有的幸福2691 days ago482

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-05-15 17:01:16

    In this case, one QuestionCtrl is enough. There is no need to create another AnswerCtrl, which complicates the problem.
    If you must use answerCtrl, you can use $emit and $brodcast to implement parent-child scope communication.
    Example

    <ul ng-controller='questionCtrl'>
        <li ng-repeat="item in list" ng-click='like(item)'></li>
    </ul>
       app.controller('questionCtrl',function(){
        $scope.list=[
        {count:10,content:"这里是答案1"},
        {count:12,content:"这里是答案2"}
        ]
        $scope.like=function(item){
            //answer function
        }
    })

    reply
    0
  • Cancelreply