1. 程式人生 > >Angular --- 自定義指令更新

Angular --- 自定義指令更新

1.左滑刪除

<li ng-repeat="name in names" drag-to-dismiss="deleteTodo($index)" >			
	……					
</li>	

app.directive('dragToDismiss', function($drag, $parse, $timeout) {
  return {
    restrict: 'A',
    compile: function(elem, attrs) {
      var dismissFn = $parse(attrs.dragToDismiss);
      return function(scope, elem) {
        var dismiss = false;

        $drag.bind(elem, {
          transform: $drag.TRANSLATE_LEFT,
          move: function(drag) {
            if ( Math.abs(drag.distanceX) >= drag.rect.width / 4) {
              dismiss = true;
              elem.addClass('dismiss');
            } else {
              dismiss = false;
              elem.removeClass('dismiss');
            }
          },
          cancel: function() {
            elem.removeClass('dismiss');
          },
          end: function(drag) {
            if (dismiss) {
              elem.addClass('dismitted');
              $timeout(function() {
                scope.$apply(function() {
                  dismissFn(scope);
                });
              }, 300);
            } else {
              drag.reset();
            }
          }
        });
      };
    }
  };
});
	


2.Jquery slideToggle()指令

<div ng-controller="slideController">
    <li ng-repeat-start="todo in todos" ng-click="$index=!$index">{{todo.name}}</li>
    <li ng-repeat-end slide-toggle="$index">{{$index}}</li>
</div>

//控制器
app.controller('slideController', function ($scope) {
	$scope.todos=[{name:'1'},{name:'2'},{name:'3'},{name:'4'}]
});

//指令
app.directive('slideToggle', function() {
	return {
		restrict: 'A',
		scope:{
			isOpen: "=slideToggle"
		},
		link: function(scope, element, attr) {
			scope.$watch('isOpen', function(newVal,oldVal){
				if(newVal !== oldVal){
					element.stop().slideToggle('slow');
				}
			});
		}
	};
});
3.$watch DOM(第二次click不執行)
<input ng-model="editArea"/>

$scope.Rewrite = function (e) {		
	$scope.$watch('editArea', function(newValue, oldValue) {
	if (newValue !== oldValue) { return } // AKA first run
		$scope.editArea = $scope.mes[e].Message
	});
}

4.多維巢狀

<div ng-app>
    <div ng-controller="test">
        <div ng-repeat="links in slides">
            <hr/>
            <div ng-repeat="link in links track by $index">
                {{link}}
            </div>
        </div>
    </div>
</div>


function test($scope) {
    $scope.slides = [
        [ 1, 1, 1 ],
        [ 4, 5, 6 ],
    ];
}