What's the correct way to trigger jQuery DOM Manipulation from within a controller?

前端 未结 2 867
青春惊慌失措
青春惊慌失措 2020-12-30 13:14

So I keep reading that jQuery manipulation from within a Controller is bad practice, but I\'m not clear on why, or how to correct.

Below is code from a Youtube tuto

2条回答
  •  时光取名叫无心
    2020-12-30 13:42

    The code showed in this post was very helpful for me to understand the relationship controller - directive, but it was throwing a js error.

    TypeError: Object function (scope) {
      $scope.items.splice(idx, 1);
      console.log($scope.items)
    } has no method '$apply'
    

    I have updated the directive slightly, and now it works to me:

    function MyCtrl($scope) {
        $scope.items = [0, 1, 2, 3, 4, 5];
    
        $scope.clearItem = function(item) {
            var idx = $scope.items.indexOf(item);
            if (idx !== -1) {
                //injected into repeater scope by fadey directive
                this.destroy(function(scope) {
    
                    $scope.items.splice(idx, 1);
    
                    //this now shows the expected results
                    console.log($scope.items)
                });
            }
        };
    }
    
    myApp.directive('fadey', function() {
        return {
            restrict: 'A', // restricts the use of the directive (use it as an attribute)
            // fires when the element is created and is linked to the scope of the parent controller
            link: function(scope, elm, attrs) { 
                var duration = parseInt(attrs.fadey);
                if (isNaN(duration)) {
                    duration = 500;
                }
                elm = jQuery(elm);
                elm.hide();
                elm.fadeIn(duration)
    
                scope.destroy = function(complete) {
                    elm.fadeOut(duration, function() {
                        scope.$apply(function() {
                            //note the change here 
                            complete(scope);
                        });
                    });
                };
            }
        };
    });
    

提交回复
热议问题