是否建议在AngularJS控制器中使用jQuery方法?

时间:2014-11-27 12:18:40

标签: javascript css angularjs angularjs-directive angularjs-scope

是否建议在AngularJS控制器中使用jQuery方法?

如果没有,我应该如何转换为AngularJS?

我知道我可以使用指令,但我需要一种干净简单的方法。

$scope.onEnabled = function (id, enabled) {

    if (enabled) {
        jQuery('#policyRuleTitle-' + id).removeClass('collapsed');
        jQuery('#policyRule-' + id).addClass('in');
        jQuery('#policyRule-' + id).css("height", "");
    } else {
        jQuery('#policyRuleTitle-' + id).addClass('collapsed');
        jQuery('#policyRule-' + id).removeClass('in');
    }
};

4 个答案:

答案 0 :(得分:3)

不,不建议用于此类用法,因为您可以在AngularJS中完全轻松完成。

这是一个很好的起点:

<div id="#policyRuleTitle" ng-class="{ collapsed: enable }"></div>
<div id="#policyRule" ng-class="{ in: enable }"></div>

https://docs.angularjs.org/api/ng/directive/ngClass

答案 1 :(得分:2)

除了二元脑回答之外,如果您需要进行复杂的DOM操作,或者只是使用本机指令无法实现的任何内容,并且它与DOM操作相关,您可以使用“指令”。

您可以创建一个自定义指令,并随意使用DOM执行任何操作。

请在此处阅读:https://docs.angularjs.org/guide/directive

答案 2 :(得分:1)

Don't mix up JQuery with AngularJS ,因为它不是一个好的做法,

如果您想更改类和样式,请使用内置的 ngClass ,AngularJS提供的 ngStyle 指令功能,而不是使用JQuery .removeClass.addClass

<强> Working Demo

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

myModule.controller('myController', function($scope) {

  $scope.areaStatus = true;
  $scope.enabled = false;
  $scope.myStyle = {
    'height': '0px'
  }
  $scope.onEnabled = function() {
    if ($scope.enabled) {
      $scope.areaStatus = true;
      $scope.myStyle = {
        'height': '0px'
      }
      $scope.enabled = !$scope.enabled
    } else {
      $scope.areaStatus = false;
      $scope.myStyle = {
        'height': '50px'
      }
      $scope.enabled = !$scope.enabled
    }
  };
});
.in {
  color: red;
}
.collapsed {
  color: green;
}
div {
  border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myModule">
  <div ng-controller="myController">
    <button ng-click="onEnabled()" ng-model="myButton">Toggle</button>
    <div ng-style="myStyle" ng-class="{'in' : !areaStatus, 'collapsed' : areaStatus}">This is some text</div>
  </div>
</div>

答案 3 :(得分:0)

实现这一目标的最佳方法是使用ng-class和ng-style。 你会在这里找到一个例子: http://jsbin.com/firosoleba/1/edit

<div id="testAngular" ng-controller="mycontroller">

    <div ng-class="div_class">Div Element</div>
    <div ng-style="{'background-color':'yellow'}">Colored Div Element</div>

</div>

angular.module('TestApp', [])
.controller('mycontroller',
    ["$scope",
    function($scope){

      $scope.div_class = "myDivClass"
      $scope.div_css = "{'background-color':'yellow'}"

    }]);