When retrieving HTML from the server, the scope values are not appearing as expected

UPDATE: After extensive testing of my code, I have gained a better understanding of what is not functioning correctly, prompting me to revise my previous inquiry.

  1. When browsing to the / directory in my local environment, my HTML file loads successfully.
  2. All pages load properly except for the content of the $scope within my directives (detailed below).
  3. I tested loading the page directly by clicking on the HTML file and was able to view the content.

The exact source of the issue remains uncertain. I have stripped down unnecessary lines from the HTML file to provide a clearer depiction of my code. The {{}} represents the templating engine language.

HTML:

<DOCTYPE html>

<html ng-app="docsSimpleDirective">
<head>
<link rel="stylesheet" type="text/css" href="/css/text.css">
<link rel="stylesheet"      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-  alpha.5/css/bootstrap.min.css" integrity="sha384-  AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi"   crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script   src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js">    </script><!-- Tether for Bootstrap --> 
<script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.min.js"></script><!-- Bootstrap --> 

</head>
<body >

<h3>Select some text </h3>
<div ng-controller="Controller">
{% for i in result %}
<div id={{i._id}} class="task" commentId = {{i._id}} get-popover- content>{{i.text}} </div>
<div id={{i._id}} class="task" commentId = {{i._id}} my-customer="customer">{{i.text}} </div> 
<br/>
{% endfor %}
</div>

<script>
(function(angular) {
'use strict';
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
   $scope.customer = {
     name: 'Naomi',
     address: '1600 Amphitheatre'
   };
 }])
.directive('myCustomer', function() {
return {
  scope: {
    myCustomer: '='
  },
template: 'Name: {{myCustomer.name}} Address:         {{myCustomer.address}}'
  };

});
})(window.angular);
</script> 
</body>
</html>

Answer №1

To create a directive with an isolated scope, use the same name for the isolated scope as the directive name:

scope: {
         myCustomer: '='
      }

Then link the controller's $scope.customer to this isolated scope like this:

<div ... my-customer="customer"></div>

Modify your template to access the data in this way:

template: 'Name: {{myCustomer.name}} Address: {{myCustomer.address}}'

Here is a sample of how it works:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<h3>Select some text </h3>
<div ng-controller="Controller">

<div id="test1" class="task" commentId="test1" get-popover-content>{{i.text}} </div>
<div id="test2" class="task" commentId="test2" my-customer="customer">{{i.text}} </div> 
<br/>

</div>

<script>
(function(angular) {
'use strict';
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
 $scope.customer = {
  name: 'Naomi',
  address: '1600 Amphitheatre'
 };
 }])
.directive('myCustomer', function() {
return {
  scope: {
     myCustomer: '='
  },
  template: 'Name: {{myCustomer.name}} Address: {{myCustomer.address}}'
};
});
  
  angular.bootstrap(document, ['docsSimpleDirective']);
})(window.angular);
  
</script>
  
</body>

Answer №2

To access your controller scope, you must include scope: { .... } inside your directive.
Controller

(function(angular) {
'use strict';
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
 $scope.customer = {
  name: 'John',
  address: '123 Main Street'
 };
 }])

HTML

// Implement this directive and pass the customer object to its scope
<my-customer customer="customer"></my-customer>

Directive

.directive('myCustomer', function() {
   return {
       scope: {
            customer: '=customer'
              }
       template: 'Name: {{customer.name}} Address: {{customer.address}}'
   };
 });

Answer №3

Enclose within

{{%  highlight %}} ... {{% endhighlight %}}

Answer №4

This approach might be more suitable for the outcome you are aiming for (note the comment suggesting an API call for your customers in JSON format).

By calling for data through an API after the page has been loaded, you can maintain your HTML/CSS/JAVASCRIPT files as completely static (no need for a templating engine) and separate from your data.

This method will result in faster loading times and provide you with the option of hosting your web front-end solely on something like a CDN (allowing your API server to focus solely on handling requests for data/sessions, etc).

<DOCTYPE html>
<html ng-app="docsSimpleDirective">
  <head>
    <!-- <link rel="stylesheet" type="text/css" href="/css/text.css"> -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi"   crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
    <script   src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js">    </script><!-- Tether for Bootstrap -->
    <script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.min.js"></script><!-- Bootstrap -->

  </head>
  <body>

    <h3>Select some text</h3>
    <div ng-controller="Controller">
      <div ng-repeat="customer in customers">
        <!-- If unsure about 'id' or 'text' values, these should be passed via API if necessary -->
        <div id={{i._id}} class="task" commentId = {{i._id}} get-popover- content>{{i.text}} </div>
        <div id={{i._id}} class="task" commentId = {{i._id}} my-customer="customer">{{i.text}} </div>
        <br/>
      </div >
    </div>

    <script>
      (function(angular) {
        'use strict';

        angular.module('docsSimpleDirective', [])
        .controller('Controller', ['$scope', function($scope) {

          // Make an API request to obtain customer data in JSON format

          // Assign the outcome to scope.customers
          $scope.customers= [
            {
              name: 'Naomi',
              address: '1600 Amphitheatre'
            },
            {
              name: 'Amir',
              address: '58 W 54th st'
            }
          ];

        }])
        .directive('myCustomer', function() {
          return {
            scope: {
              myCustomer: '='
            },
            template: 'Name: {{myCustomer.name}} Address: {{myCustomer.address}}'
          };
        }); // directive
      })(window.angular);

    </script>

  </body>
</html>

You could also simulate a REST API server by sending a request to a static file like this:

 $http.get("./myFakeAPI.json").then(function(response){
  $scope.customers = response.data.customers;
});

The contents of the file 'myFakeAPI.json' would resemble:

{
  "customers":
    [
      {
        name: 'Naomi',
        address: '1600 Amphitheatre'
      },
      {
        name: 'Amir',
        address: '58 W 54th st'
      }
    ]
}

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

time interval between closing angularjs modal and redirection

I'm currently utilizing an AngularJS modal, however, when I need to redirect to another view, I find myself having to close it and add a delay to hide the shadow before transitioning to the new page. Is there a faster solution available? I'm usi ...

Utilizing pure JavaScript to dynamically fetch HTML and JavaScript content via AJAX, unfortunately, results in the JavaScript

I am trying to load an HTML file using AJAX and then execute a script. Here is the content of the HTML file I want to load: <div class="panel panel-body"> <h4>Personal Data</h4> <hr /> <span data-bind="editable: firs ...

Guide on extracting only numerical data from an array of objects for the purpose of calculating total amounts. Unveiling the challenge of building an

I am new to JavaScript and in need of assistance with a particular challenge. How can I extract the "numbers" only from an array containing object values, sum them up, and display the total? Below is the code related to this query; everything that follows ...

Transforming an established Angular application into a Progressive Web App

What steps do I need to take in my command line to transform my Angular project into a progressive web app (PWA) similar to react-pwa? ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...

Create a PDF document using the combined HTML content

I am facing an issue with generating a PDF from HTML content. My goal is to convert all the content within a specific div into a PDF. I have tested out a few converters, but they only seem to convert HTML files. I do not want to convert the entire HTML fi ...

"Exploring the Constraints of MongoDB's Range Functionality

I am facing an issue with my nodejs and mongodb setup. I am trying to search for documents within a specific number range but the function is returning results outside of that range. Here is an example of my code where I am attempting to retrieve documents ...

Finding the index of a clicked link using jQuery

This is the code I have written: <div> <h2><a href="link-here">Link Text</a></h2> <p>Description</p> <h2><a href="link-here">Link Text</a></h2> <p>Description</p> <h2>< ...

What do the different states of AngularJS promises refer to?

Other than success and error, are there additional states that we can handle when using $http get rest promise? I remember seeing more than just these 3 states in a raw response logged in the console before, but I'm not sure which ones. ...

ng-binding does not sync with input field

Check out this JavaScript snippet angular.module('myApp') .controller('HeaderCtrl', function($scope) { $scope.searchBooking = "test"; $scope.goToBooking = function() { console.log($scope.searchBooking); ...

Subheaders that stay in place while scrolling through a table with a stationary header

My goal is to design a table with a fixed header that allows the body to scroll under the header. While this is a common design, I am facing the challenge of implementing sticky subheaders. These subheaders should scroll along with the table until they rea ...

What could be causing my YouTube code to malfunction with certain playlists?

Check out the first jsfiddle playlist here The Alum Songs Playlist is working perfectly, but unfortunately, the same code is not functioning for another playlist ID. View the second jsfiddle playlist here The Medical Animated Playlist is currently not w ...

Validating passwords using Vuetify

I am implementing password validation on my form using Vuetify validation rules: passwordRules: [ v => (v && v.length >= 1 && v.length <= 10) || 'Password length should be between 1 and 10', v => (v && v.l ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Error encountered during Jasmine testing: [$injector:unpr] Provider not recognized:

Here is the code snippet I'm working with: angular.module('ps.workspaces').config(['$provide', function($provide) { $provide.factory('workspacesNonCompliance', ['$filter', function($filter) { return { ...

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet: function sampleFunction(sample:string|number|string[]) { if(typeof sample == "string") { console.log("Sample is String " + sample); } else if(typeof sample == "number") { console.log("Sample is Number " + sampl ...

What is the best way to effectively link promise calls that rely on each other?

Here is the code snippet I am currently working with: const request = require('request-promise'); request(validateEmailOptions).then(function(result) { if (result.valid) { request(createUserOptions).then(function (response) { if (re ...

What is the best way to add request body data to a MySQL database when using express js?

Currently, I am in the process of creating a small API using Express JS and MySQL. After following an online tutorial on integrating MySQL with Express, I attempted to develop this API and test it using Postman. In order to insert data received through Pos ...

`Nav arrow positioning problem in absolute position`

I'm experiencing an issue with the left navigation arrow in a portfolio viewer I'm using. It seems to be moving along with the window size and I can't seem to find a way to keep it contained within my div and stationary. The plugin responsib ...