angularjs directive 的几点使用技巧

传递参数给directive

<my-dir myindex="$index" title="t1"></my-dir>

app.directive('myDir', function () {
  return {
    restrict: 'E',
    scope: {
      myindex: '=',
      title: '@'
    },
    template:'<div>{{myindex}}</div>',
    link: function(scope, element, attrs){
      console.log('test', scope.myindex)
    }
  };})

参数绑定根据须要,提供如下几种功能:css

  • = is two-way bindingapp

  • @ simply reads the value (one-way binding)spa

  • & is used to bind functionsrest

DOM元素动态绑定CSS

可使用ng-class命令,判断逻辑条件来动态的绑定css class给tag,基础语法为:code

option 1:
function ctr($scope){
   $scope.test =“classname”;
}

<div class=”{{test}}”></div>

option 2:
function Ctr($scope) { 
    $scope.isActive = true;
}

<div ng-class="{true: 'active', false: 'inactive'}[isActive]"></div>

option 3:
function Ctr($scope) { 

}

<div ng-class = "{option.selected == 'active' ? 'active' : 'inactive'}"></div>

也能够用angular.element (jqLite)来实现此功能:orm

var ele = document.getElementById(scope.subPhaseId);
angular.element(ele).addClass('active');

angular.element接受String参数或DOM元素。也可直接用.css("k:v")绑定css style。element

相关文章
相关标签/搜索