2014-03-03 5 views
9
다음

에 NG-불확정 속성에 대한 지시문은 체크 박스에서 불확실한 상태를 처리하는 지침입니다 단순히 필요AngularJS와 사용자 정의 체크 박스

<ul ng-repeat="item in data"> 
    <li> 
     <input type="checkbox" ng-indeterminate="{{item.displayed > 0 && item.displayed < item.total}}" ng-checked="item.displayed > 0" /> 
     {{item.name}} ({{item.displayed}}/{{item.total}}) 
    </li> 
</ul> 

일없이 NG-불확실한 표현을 쓸 수있는 방법이 있나요 e 이중 - 곱슬 표기법, 네이티브 - 체크 하나?

ng-indeterminate="item.displayed > 0 && item.displayed < item.total" 

내가 시도 :

.directive('ngIndeterminate', function($compile) { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attributes) { 
      attributes.$observe('ngIndeterminate', function(value) { 
       $(element).prop('indeterminate', $compile(value)(scope)); 
      }); 
     } 
    }; 
}) 

그러나 나는 다음과 같은 오류 얻을 :

Looking up elements via selectors is not supported by jqLite! 

Here is a fiddle 당신이 함께 플레이 할 수 있습니다.

+0

이런 식으로 뭔가? http://jsfiddle.net/d9rG7/1/ –

답변

10

우선 앞에 jQuery 을로드하면 element을 jQuery로 랩핑 할 필요가 없습니다. 따라서 지시문 안에 $(element)을 사용할 필요가없고 대신 element을 각도로 사용하면 자동으로 element을 jQuery 객체로 래핑합니다.

예를 들어 실제로는 jQuery가 필요하지 않기 때문에 아래에 제공된 대답은 jQuery에 전혀 의존하지 않습니다.

귀하의 질문에 대해 $watch 속성 값은 angular가 컴파일 된 속성 값을 자동으로 반환합니다. 그래서 당신과 다음 작품을 기대 : 직접 변경하는 속성 http://jsfiddle.net/d9rG7/5/

+0

'.prop'는 jQuery 메소드이고'element'는 jQuery 객체이기 때문에 당신은 jQuery에 의존한다. 당신은'element [0] .indeterminate = !! value'를 사용하여 그것을 떼어 낼 수 있습니다, 그러나 이것이 향상인지 확실하지 않습니다. – punund

+1

@punund'.prop'는 jqLite의 일부이므로 jQuery가 필요 없습니다. https://docs.angularjs.org/api/ng/function/angular.element – Beyers

+0

BTW, ng-indeterminate는 이제 angular-ui utils의 일부입니다. : http://angular-ui.github.io/ui-utils/ –

4

사용 scope.$evalelement.prop :

.directive('ngIndeterminate', function() { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attributes) { 
      attributes.$observe('ngIndeterminate', function(value) { 
       element.prop('indeterminate', scope.$eval(value)); 
      }); 
     } 
    }; 
}); 

FIDDLE


다음
.directive('ngIndeterminate', function($compile) { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attributes) { 
      scope.$watch(attributes['ngIndeterminate'], function (value) { 
       element.prop('indeterminate', !!value); 
      }); 
     } 
    }; 
}); 

jsfiddle 작업입니다attributes.$observe을 사용하면 보간을 포함하는 속성 변경 (예 : {{}} ') 만 잡을 수 있습니다. "표현식"을 관찰하거나 볼 수있는 scope.$watch을 사용해야합니다. 그래서, @ 바이어스 대답이 더 정확하다고 생각합니다. @Chi_Row에 주목하는 Thx

+0

$ observe는 변경 사항을 통지하지 않는 것 같습니다. 이유가 뭐야? [바이올린 예제] (http : // jsfiddle.net/csrow/YzT2W/1 /) –

+0

괜찮 았기 때문에 $ observer는 ngInterterminate 속성에 삽입 된 값이 없으므로 변경 사항을 알지 못합니다. 따라서 물체가 변화하더라도 $ 관찰은 시작되지 않습니다. $ watch는이 경우 변경을 알리는 올바른 방법입니다. –

+0

지적 해 주셔서 감사합니다. – sp00m

관련 문제