2

我的項目已經沒有jquery依賴,所以我想給jquery代碼轉換爲純angular jsjavascript,這就是我需要轉換主要是想jQuery的代碼轉換爲純JavaScript或AngularJS

var container = $('.dynamic-content'); 
container.html('<div ng-controller="TempCtrl"> <h2>About</h2> <h3>{{total}}</h3> <p>Testing the total</p> <button ng-click="update()">Update</button> </div> <script> console.log("begin"); console.log(app.controller); app.controller("TempCtrl", function ($scope) { $scope.total = 0; console.log("inside"); $scope.update = function() { $scope.total = $scope.total + 1; }; }); console.log("end") <\/script>');     
var newScope = angular.element(container).scope(); 
var compile = angular.element(container).injector().get('$compile'); 
compile($(container).contents())(newScope); 

,這是我plunker Pure Angularjs

回答

0

什麼,我看你需要使用document.queryselector這種方法會做選擇的元素

的伎倆

,如果你想尋求的jQuerynative javascript更多的表達,您可以檢查this site

0

我很奇怪,爲什麼你有這樣的混合代碼庫。但這裏是:Plunker

使用ng-show顯示/隱藏動態內容:

<div class="dynamic-content" ng-show="loaded"> 
    <h2>About</h2> 
    <h3>{{total}}</h3> 
    <p>Testing the total</p> 
    <button ng-click="update()">Update</button> 
</div> 

而且不需要TempCtrl,只需移動方法update()控制器AppCtrl

=============

根據要求,重寫了它使用的指令,而不是(Plunker)。該指令是這樣的:

.directive('myDirective', function() { 
    return { 
     restrict: 'AE', 
     template: '<div><h2>About</h2><h3>{{total}}</h3><p>Testing the total</p><button ng-click="update()">Update</button></div>', 
     controller: ['$scope', function($scope) { 
     $scope.total = 0; 
     $scope.update = function() { 
      $scope.total += 1; 
     }; 
     }] 
    }; 
    }); 

這樣使用它:

<div class="dynamic-content" ng-if="loaded"> 
    <div my-directive></div> 
</div> 
+0

,但我得到了'html'在字符串'script'標籤 –

+0

沿然後你需要一個指令。如果你想在別的地方重用這段HTML,你可以使用它。 – Joy

+0

是的,我甚至做到了這一點,但angularjs代碼不工作時,這樣做....這裏是我的plunker https://jsfiddle.net/fLa9o1pe/9/ –