3

I'm totally new to angular and I'm finding that doing simple things aren't as obvious to me? I have a list of items that I display using ng-repeat. I simply want to hide the element once I click on an element within that scope. I'd like to do it the "angular" way with good practices.. just not sure what that is.

This is html

<div ng-app="myApp">
    <div ng-controller="FruitsCtrl">
        <ul>
            <li ng-repeat="fruit in fruits">
                <p>{{fruit.name}}</p>
                <button ng-click="hideMe()">hide li</button>
            </li>
        </ul>
    </div>
</div>

This is my js

var myApp = angular.module('myApp', []);

myApp.factory('Fruits', function () {
    var Fruits = [{
        name: "banana"
    }, {
        name: "watermelon"
    }, {
        name: "strawberry"
    }];

    return Fruits;
});


function FruitsCtrl($scope, Fruits) {
    $scope.fruits = Fruits;

    $scope.hideMe = function () {
        alert('hide this li');
    };
}

I have this on jsfiddle: http://jsfiddle.net/hS5q8/2/

Help or direction would be great! Thanks!!

1 Answer 1

4

You can use ngHide directive. In Example added a property hide, ngHide will hide li if this property is true.

HTML

<li ng-repeat="fruit in fruits" ng-hide="fruit.hide">
    <p>{{fruit.name}}</p>
    <button ng-click="hideMe(fruit)">hide li</button>
</li>

Angularjs Method

$scope.hideMe = function (fruit) {
    fruit.hide=true;
    alert('hide this li');
};

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

I was wondering how that worked with ng-hide. Thank you!! Works great!
I think you can also skip the function: ng-click="fruit.hide=true"
@FooL, But OP might need to do some operations in that method
@Satpal, true, this is a good gold plated answer. i'm trying to provide the simplest answer to the original question "how do I hide the element when clicked?" :) both works
@FooL, I totally agree with your solution and that will work. No doubt in that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.