Issue of jQuery with AngularJS - ngRepeat on Object with Wrap Function
by kelvinau
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.angularjs.org/1.6.10/angular.min.js"></script>
<h2>
Issue of AngularJS with jQuery - ngRepeat on Object with Wrap Function
</h2>
<div>This is a demo for my blog <a href="https://kelvinau.net/2018/06/05/issue-of-angularjs-with-jquery-ngrepeat-on-object-with-wrap-function/" target="_blank">here</a>.</div>
<span>
</span>
<hr>
<!-- AngularJS -->
<div ng-app="angular-app" ng-controller="controller">
<b>AngularJS 1.6.10</b>
<button ng-click="reset()">
Reset allTexts
</button>
<div>
<span add-wrapper ng-repeat="(key, textObj) in allTexts">{{textObj.label}}</span>
</div>
</div>
<!-- End of AngularJS -->
<hr>
<!-- VueJS -->
<div id="vue-app">
<b>VueJS 2.5.16</b>
<button @click="reset">
Reset allTexts
</button>
<div>
<div>
<span v-add-wrapper v-for="(textObj, key) in allTexts">{{textObj.label}}</span>
</div>
</div>
</div>
<!-- End of VueJS -->
CSS
html {
background-color: white;
}
span {
color: red;
}
.wrapper span {
color: black;
}
JavaScript
var allTexts = {
'one': {
label: 'Text 1',
},
'two': {
label: 'Text 2',
},
};
/* var allTexts = [{
label: 'Text 1'
}, {
label: 'Text 2'
}]; */
/*
* AngularJS
*/
angular.module('angular-app', []).controller('controller', function($scope) {
$scope.allTexts = JSON.parse(JSON.stringify(allTexts));
$scope.reset = function() {
$scope.allTexts = JSON.parse(JSON.stringify(allTexts));
}
})
.directive('addWrapper', function() {
return {
restrict: 'A',
/* replace: true,
transclude: true,
template: '<div class="wrapper"><span ng-transclude></span></div>', */
compile: function() {
return {
pre: function() {
console.log('Before child element is linked');
},
post: function(scope, elem) {
console.log('After child element is linked');
elem.wrap('<div class="wrapper"></div>');
}
}
},
link: {
pre: function() {
console.log('Before child element is linked');
},
post: function(scope, elem) {
console.log('After child element is linked');
elem.wrap('<div class="wrapper"></div>');
}
},
}
});
/*
* VueJs
*/
new Vue({
el: '#vue-app',
data: {
allTexts: JSON.parse(JSON.stringify(allTexts)),
},
methods: {
reset() {
this.allTexts = JSON.parse(JSON.stringify(allTexts));
}
},
directives: {
addWrapper: {
inserted: function(elem) {
$(elem).wrap('<div class="wrapper"></div>');
}
}
}
})