Error encountered while attempting to compile transcluded directives during unit testing with Angular version 1.3.0

I am facing an issue with a custom directive having transclude: true property. The directive contains a template pointing to a simple HTML file with an anchor element having an ng-transclude attribute. The anchor element wraps the content of the directive.

Here is how my test script looks like:

describe('foobar directive', function() {
    var $compile, $rootScope, $modal;

    beforeEach(module('collective'));
    beforeEach(module('test.templates'));

    beforeEach(inject(function(_$rootScope_, _$compile_, _$modal_) {
        $rootScope = _$rootScope_;
        $compile = _$compile_;
        $modal = _$modal_;
    }));

    it('attempts to open the modal when the wrapped element is clicked', function() {
        spyOn($modal, 'open');

        var el = $compile('<foo-bar><div id="foobar"></div></foo-bar>')($rootScope);
        $rootScope.$digest();

        el.find('#foobar').click();
        expect($modal.open).toHaveBeenCalled();
    });
});

I am using ng-html2js-preprocessor to load templates into the test.templates module, and it works for all non-transcluded directives.

However, the test fails as $modal.open() is not being called. The issue lies in the fact that the anchor element in the template is not added to the element after compilation. This problem started with Angular 1.3.0 and persists in Angular 1.3.5.

After compiling in my test, the element looks like:

<foo-bar class="ng-scope">
   <div id="foobar"></div>
</foo-bar>

But it should look like this:

<foo-bar class="ng-isolate-scope">
   <a href="#" ng-click="blah blah">
      <div id="foobar"></div>
   </a>
</foo-bar>

The latter is true for 1.2.9 but not for 1.3.0.

Any insights on what could be causing this error?

Answer №1

After testing with Angular versions 1.3.0 and 1.3.5, I can confirm that compiling directives with transcluded content works perfectly for me in both scenarios. I conducted the compilation in the karma test environment, just like you did.


Have you considered that the issue might not necessarily lie with ng-transclude?

Answer №2

Shoutout to @artur for bringing to my attention that the issue stemmed from a subtle change in behavior that was introduced in Angular 1.3.0.

It turns out that a service I had injected was causing Angular to have issues compiling the directive in my testing environment. This particular dependency was a small factory I had created to make a window property an injectable service. Since I didn't actually use this service in my tests, I didn't import the underlying library in my karma config, resulting in the window property being undefined. Interestingly, Angular 1.2.x didn't have an issue with this, but 1.3.x had trouble compiling.

For instance, consider this factory:

myModule.factory('bootbox', function() {
    return window.bootbox;
});

...and this directive:

myModule.directive('myDirective', ['$scope', 'bootbox' function($scope, bootbox) {
   //...
}]);

In Angular 1.2.x, the above directive would compile even if window.bootbox was undefined, but in 1.3.x, it would not. Surprisingly, a null value didn't pose the same problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS to show content based on a callback function

I'm a beginner in angular and it seems like I might be overlooking something. For the registration form, I need users to provide their location. Depending on whether they allow/support navigator.geolocation, I want to display a drop-down menu for cho ...

Incorporating AngularJS to load an HTML snippet with a keyboard press of the

I am currently developing my first angularjs application. One of the features I am working on is a search input that will load a page and show the contents. <input ng-enter="doSomething()" type="text" ng-model="drugSearch" datasets="drugSearchDa ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

iOS alert notification for navigator

How can I fix the issue with my alerts not working on my iOS project? I am using Ionic and AngularJS to develop my app. The problem I am facing is that when the alert pops up, the title shows as "index.html". This is how I call the alert: alert("aaa"); ...

Creating an expandable discussion area (part II)

After checking out this query that was posted earlier, I am interested in implementing a similar feature using AJAX to load the comment box without having to refresh the entire page. My platform of choice is Google App Engine with Python as the primary lan ...

Obtain an array of images from the Google Places API through a nearby search functionality

Utilizing the Google Places API within a JSP to retrieve JSON data in JavaScript has been successful, except for one aspect - the photos. Despite using the nearbySearch function, the PlacePhoto object is not populating as expected. Here is the nearbySearc ...

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

Utilizing JavaScript to implement a single method across multiple objects

Recently, I encountered a problem while trying to use the prototype method to apply the same function or variable to multiple objects. Despite creating numerous objects in the following manner: var item = { a: { aa: "lalala", ab: 1, somethin ...

Generate a unique sequence not functioning

I'm attempting to generate a unique string composed of random characters, similar to the example found at this source. $(document).ready(function(){ $('#randomize').click(function() { var str = ""; var possibleChars = "michaeljo ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Empty the localStorage when terminating the IE process using the Task Manager

Utilizing HTML5 localStorage to keep track of my application session has been a useful feature. Here is a snippet of the code I am currently using: if(typeof(Storage)!=="undefined") { if(sessionStorage.lastname=="Smith") { alert("Your ses ...

Having trouble parsing PHP JSON encoded data in JavaScript

When I make an AJAX call to a PHP script that returns a JSON encoded object, I encounter some issues. $.post("php/getCamera.php", { cam_id: identifier }, function(data){ console.log(data); //var camera = JSON.parse( ...

Using environment variables in next.config.js allows for successful connection to the database, however, when attempting to use a

Utilizing the serverless-mysql library, I have successfully connected my next app to a remote MySQL DB through an SSH tunnel with the ssh2 library. Although everything is functioning properly, I am looking to enhance the security of my code by removing the ...

What is the best way to transfer a list from aspx to javascript?

When populating a table by looping through a list, I aim to pass a row of data to my JavaScript code. If that's not an option, I'd like to pass the list and the ID number for the specific row. How can I achieve this? <%foreach(var item in Mod ...

Vuejs dropdown selections are not working as expected due to a bug

My dropdown menu is being populated with options based on an API response that looks like the following: {"value":"1371","label":"apple"},{"value":"1371","label":"banana"},{&qu ...

Problem with jQuery form button in dynamic table detecting rows after the first

I am currently working on a file that generates a dynamic table based on the records in a database. Each row in the table has a button to delete that particular row. The code I have written works perfectly for the first row, but it fails to detect the row ...

Troubleshooting JavaScript Functions Failure Following AJAX XML Request

My current project involves developing an interactive map where users can select a year from the timeline and apply filters. This functionality is achieved through XML HttpRequest, which refreshes the SVG each time a selection is made. The SVG code for th ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

What is the best way to combine two arrays while ensuring the elements of the second array appear before the elements of the first

Is there a way to concatenate two arrays in JavaScript, where the second array appears before the first? For example: const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combinedArr = arr1.concat(arr2); console.log(combinedArr); I am aware that yo ...

403 Malicious Path Middleware Error in Express.js

Encountering an error when sending a post request to my server, but only on the production server - whereas the staging server is functioning properly. Both servers are hosted on AWS Ubuntu instances. Investigating the stack trace, it appears that the err ...