jQuery中的AngularJS范围

AngularJS scope in jQuery

本文关键字:范围 AngularJS 中的 jQuery      更新时间:2023-09-26

有没有办法在jquery中使用angularjs?我有以下代码:

$scope.reloadContainer = 
        function(){
            <div class="thumbnail box gameThumbnail" ng-repeat="image in images" gameId=" {{image.GameID}}|{{image.MachineID}}" gameName="{{image.MachineDescription}}" gameDesc="{{image.LongDescription}}">';
            $scope.images = [$scope.images[0]];
            string += '<div class="game-title">{{image.MachineDescription}}</div>';
            angular.element($("#games-container")).scope().$apply();
            $("#games-container").append(string);
        };

附加字符串后,它仅显示 {{图像。MachineDescription}} 在前端。谁能帮我弄清楚这一点?谢谢。

你可以在jquery中使用angularjs,但我警告你这不是最佳实践,因为你可以用jquery做任何你想做的事情,你应该总是在指令/服务中这样做,但你应该避免在控制器中像jquery这样的事情,这是一个不好的做法。

但是如果你没有其他选择(我有这样的场景,但你的情况看起来不像极端情况(,你总是可以通过捕获一个元素并使用 scope(( 函数来获取父控制器/指令的作用域,如下所示:

您始终可以使用以下命令获取 DOM 元素的范围:

var $scope = angular.element("domElement").scope();

调用编译服务

var html = $compile('<div>some HTml</div>')($scope); //you need the scope to compile the html
angular.element('#parent').append(html); //appending the html with all the events.

但是,此解决方案是您没有选择的时候。您应该使用ng-hide和ng-if在需要时显示(我可能是错的,但我认为您可以在问题中使用它们(。仅当您从其他来源获取html时才使用该解决方案,该来源提供静态html,但要求您在前端对html执行角度内容,这种情况很少见。