ng-click后可以触发ng-class?

时间:2015-03-24 15:16:57

标签: javascript angularjs

我有以下元素:

<a href="" ng-click="project.hasPhotos? removeFromProject(project, $index, currentPhoto) : addToProject($index, currentPhoto)" ng-class="{'selected-project': (belongsPhotoToProject(project, $index, currentPhoto) || project.hasPhotos)}">{{ project.label }}</a>

ng-class的想法是:如果照片属于项目,则函数belongsPhotoToProject返回true,因此设置了selected-project类。现在,点击后,在触发函数removeFromProject(project, $index, currentPhoto)后,belongsPhotoToProject不再评估为true,所以我希望它删除该类,但是,这不会发生

所以我的问题是:在初始页面加载后,哪些页面事件会被ng-click触发?如果ng-click仅在页面加载时触发,我可以在ng-click上再次手动触发吗?

1 个答案:

答案 0 :(得分:2)

这应该像你描述的那样工作。这是一个展示它的人:

http://plnkr.co/edit/V4R0EUwKK5TeH5wn7Y5N?p=preview

您的浏览器是否收到任何错误?

的javascript:

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.project = {
    hasPhotos: true,
    label: "My Test Project"
  };

  $scope.removeFromProject = function(project, $index, currentPhoto) {
    $scope.project.hasPhotos = false;
  };

  $scope.addToProject = function($index, currentPhoto) {
    $scope.project.hasPhotos = true;
  };

  $scope.belongsPhotoToProject = function(project, $index, currentPhoto) {
    return $scope.project.hasPhotos;
  };

});

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <a href="" ng-click="project.hasPhotos? removeFromProject(project, $index, currentPhoto) : addToProject($index, currentPhoto)" ng-class="{'selected-project': (belongsPhotoToProject(project, $index, currentPhoto) || project.hasPhotos)}">{{ project.label }}</a>
  </body>

</html>

css:

.selected-project {
  background-color: #ccf;
}