Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using Angular JS. I loop out a part of a scope that from the start is a JSON array.

I need to check for if a value in that array exists. If it does it should do something. The following code work but I can't figure out a way to save "status" temporary.

<div ng-repeat="item_value in item['slug'].values">
    {{item_value}}
    <div ng-if="item_value == 'dogs_cats'">
        Somehow save "status" to true when above is equal.
    </div>
</div>
<div ng-if="status == 'true'">
    Do someting here.
</div>

Maybe my approach is wrong. Maybe this should not go in the template? I like different solutions to choose from and suggestions on which would be prefered.

share|improve this question
    
Stop approaching this procedural style and start thinking AngularJS :) ng-show="item_value == 'dogs_cats'" ? –  Sergiu Paraschiv Jun 27 '14 at 9:20

2 Answers 2

I think something like this would do:

<div ng-if="item_value == 'dogs_cats'" ng-init="status = true">
    Somehow save "status" to true when above is equal.
</div>

But preferably you should put that logic in controller

share|improve this answer
    
{{status}} worked this way, but only inside the first ng-if, not outside of it. –  Jens Törnell Jun 27 '14 at 9:35
    
OK, what's really the status here, what you are trying to achieve?, save the status for current item or global? –  maurycy Jun 27 '14 at 9:57

You should refactor some of this into a controller. Try something like:

HTML:

<div ng-controller='itemSlugs'>
    <div ng-repeat="item_value in item['slug'].values">
        {{item_value}}
    </div>
    <div ng-if="status">
        Do something here.
    </div>
</div>

Javascript:

angular.module('myApp', []).
    controller('itemSlugs', ['$scope', function($scope){
        $scope.item.slug.values = [ /*initialize here*/ ];
        $scope.status = false;
        $scope.$watch('item.slug.values', function(){
            $scope.status = false;
            $scope.item.slug.values.forEach(function(item_value){
                if (item_value == 'dogs_cats'){
                    $scope.status = true;
                }
            });
        });
    });

I added a watch so if any values in your item.slug.values changes, then the status will update accordingly.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.