简体   繁体   中英

Store first element of ng-repeat directive

Im new to Angular..

I have a ng-repeat directive and I would like to store one of the answer attribute in a "global" variable.

I would like someting like this

var buffer = answer.discussionId;
<div ng-repeat="answer in answers">
    if(buffer != answer.discussion){
        //do something
        buffer = answer.discussionId;
    }    
</div>

Thank you

I am sure there will be a hack to do this. But you should never do this in angular. Do it in your controller!

With angular the idea of doing conditional logic within your view is discouraged. You should really be doing any storing of data via your controller/model or through the use of directives.

http://docs.angularjs.org/guide/directive

If I understood your problem correctly this will be the "angular way" to do this:

You need to create a watch to find when the value you spec has changed.

app.controller('myCtrl',['$scope',function($scope){
    "use strict";
    $scope.buffer ="";
    $scope.answers = [{ /*some object we do not know*/ }];

          $scope.$watch("answers",function(newValue, oldValue, scope){
                  var result =newValue.filter(function(answer){
                       return ($scope.buffer !== answer.discussion);
                  });
                  if (result.length > 0){
                      $scope.buffer = result[0].discussionId;
                  }
          },true);
}]);

For more information watch click here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM