With AngularJS, how can I conditionally add a clas

2019-07-26 02:53发布

My jQuery code looks like:

  $("body").on("click", ".nav-bar", function(e){
    $(".my-nav").addClass("open");
  });

I want to angular-ify this. There are a few different controller / views that will have a .nav-bar class, so I'm pretty sure I'll have to use a directive. I'm just not sure how to do that. Ideally, I can strip away all jQuery.

Thanks

2条回答
看我几分像从前
2楼-- · 2019-07-26 03:19

In angular, you usually don't add classes based on action, but rather based on the status of your app. For example, if you were select one of many items in a list, you could change it's selected attribute to "true".

For example:

$scope.items = [{id: 1, name: "test", selected: false}, {id: 2, name: "test 2", selected: true}, {id: 3, name: "test 3", selected: false}]

Then in your template, you will use ng-class to let angular handle changing classes:

<ul>
  <li ng-repeat="item in items" ng-class="{ selected: item.selected }">{{item.name}}</li>
</ul>

In the case of your navbar, I would actually think about your app state. Is this navbar reflective of your current location in the app? If that's the case, you should start checking your $routeParams (or $stateParams if you use the excellent ui-router) and conditionally adding classes that way.

The point here is that angular-fying an app is more than porting jQuery actions; it's about building a smarter app.

查看更多
The star\"
3楼-- · 2019-07-26 03:31

Create a directive:

.directive("navbarAction", function() {
    return {
        restrict: 'A', //<---Look up what this does, there are other options
        link: function(scope, elem, attrs) {
            //Using jQuery
            $(elem).click(function() {
                $(".my-nav").addClass("open");
            });
        }
    }
});

Then in your .nav-bar element, add a navbar-action attribute.

Sample:

<input type='button' value='Click me!' navbar-action />

Angular also comes with jqLite, (you guessed it, a lite version of jQuery), so before importing the entire jQuery lib, see if you can accomplish what you need with jqLite.

查看更多
登录 后发表回答