Christopher Christopher - 1 month ago 17
reST (reStructuredText) Question

AngularJS change variable form view on ng-if

Ok, so I have a basic variable.

$scope.categoryHeader = "";


I'm trying to group lists by their category. How do I update the variable from the view? Or is there a better way to accomplish this?

<div ng-app="SharePointAngApp" class="row" style="color:white">
<div ng-controller="spCustomerController">
<ul ng-repeat="item in items">
<div ng-if="item.Category.Title != categoryHeader" ng-change="categoryHeader = item.Category.Title">
<h4>{{item.Category.Title}}</h4>
</div>
<li>
<a href="{{item.File.ServerRelativeUrl}}">{{item.Title}}</a>
</li>
</ul>
</div>
</div>


Example



Category1




  • item1

  • item2

    Category2


  • item3


Answer

I would call a function on ng-if, so that i can persist the value too in my scope variable too based on my condition. you could persist your $cope.categoryHeader when it returns false.

<div ng-app="app" ng-controller='ctrl'>
<div ng-repeat=" item in num"> 
    <div ng-if="display(item)" >  
        display this
    </div>
</div>
</div>

angular.module('app', [])
.controller('ctrl', function($scope) {
    $scope.num = [1,2,3];
    $scope.display = function(x) {
        if (x === 2) {  
            return true;
        } else {
            return false;
        }
    };
});

A sample fiddle: http://jsfiddle.net/63raz38t/1/

Comments