Javascript 如何在AngularJS中正确使用指令

Javascript 如何在AngularJS中正确使用指令,javascript,angularjs,Javascript,Angularjs,我正在用AngularJS的指令做我的第一步,而这个指令对我不起作用 我有一个ng repeat列表 <ul ng-after-list-filter> <li ng-repeat="item in items | filter:activeFilter.filterType = activeFilter.filterValue">...</li> </ul> 如何使其工作?我假设scope.activeFilter.filterValu

我正在用AngularJS的指令做我的第一步,而这个指令对我不起作用

我有一个
ng repeat
列表

<ul ng-after-list-filter>
    <li ng-repeat="item in items | filter:activeFilter.filterType = activeFilter.filterValue">...</li>
</ul>
  • 如何使其工作?我假设scope.activeFilter.filterValue没有被更新,但是-它在作用域中,它会被更新,列表也会被过滤。我试图观察这个变量,为什么它不起作用

  • 是否有更好的方法来创建此指令?我的意思是-我希望在列表更新时运行DOM更改(调整事物的大小)。那么,有没有办法收听
    $('ul').html()
    ?我试过了,但它输出了一个错误,我将原始文本放入javascript


  • 似乎要重用筛选器中的筛选值?对吗

    如果是这样的话,您真正需要做的就是:

    <!-- initial filter -->
    <ul ng-after-list-filter>
        <li ng-repeat="item in filteredData =  (items | filter:activeFilter.filterType)">{{item}}</li>
    </ul>
    
    <!-- reuse what you filtered -->
    <div ng-repeat="item in filteredData">{{item}}</div>
    

    $last可用于确定创建最后一个
  • 的时间。有关可附加到
  • 元素的checkLast指令的实现,请参见(我没有编写):

    directive('checkLast', function () {
      return function (scope, element, attrs) {
         if (scope.$last === true) {
            element.ready(function () {
               // manipulate ul here, or if that doesn't work
               // try with $timeout:
               // $timeout(function() { 
               //    do manip here
               //}, 0, false);  // remove false if you need $apply to run
    
    另见


    我不确定element.ready()是否必要,或者它是否适用于动态生成的元素。

    我不明白为什么要复制列表?现在我有两个列表而不是一个,我仍然不知道当列表完成更改后如何触发函数。哦,对不起,我想我不明白你的问题。如果需要知道列表何时被过滤,可以向上面的
    filteredData
    参数添加$watch;希望这是个打字错误,你的意思是==?
    myModule.directive('ngAfterListFilter',function(){
        return {
            restrict: 'A',
            link: function(scope,element,attrs) {
                scope.$watch('filteredData', function(val) {
                    console.log('do something here');
                });
            }
        }
    });
    
    directive('checkLast', function () {
      return function (scope, element, attrs) {
         if (scope.$last === true) {
            element.ready(function () {
               // manipulate ul here, or if that doesn't work
               // try with $timeout:
               // $timeout(function() { 
               //    do manip here
               //}, 0, false);  // remove false if you need $apply to run