Adding a directive with an ng-click dynamically

UPDATE: view the demo on Plunker: https://embed.plnkr.co/fHPQfbUQ1lvZBJsDNQR5/

An issue arises when I try to include my directive in my HTML code, triggering an error:

"http://errors.angularjs.org/1.5.6/$parse/syntax?p0=%7B&p1=invalid%20key&p2=17&p3=updateTypeZone(%7B%7Bcount%7D%7D)&p4=%7Bcount%7D%7D"
appears when I click the button.

This is a snippet of my controller:

connectItApp.controller('Inputcontroller',['$scope','$http', '$compile' , function($scope, $http, $compile) {
 $scope.count = 1;

 $scope.addInput = function(){

  angular.element(document.getElementById('box')).append($compile("<new></new>")($scope));
  $scope.count++;
 }

 $scope.updateTypeZone = function (concernedId) {
    /*some stuff */
}]);

In this section, two directives are defined within a div using Inputcontroller as the controller:

connectItApp.directive('champText', function(){
 return{
  restrict: 'E',
  template:     '<button type="button" class="btn btn-default btn-lg btn-block" ng-click="addInput()" >'+
  '<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span><span style="margin-left:10px;">Text</span>'+
  '</button>'

 };
});

connectItApp.directive('new', function($compile){
 return{
  restrict: 'E',
  templateUrl: 'views/new-input.html'

 };
});

The content of views/new-input.html is shown below:

<div ng-click='updateTypeZone({{count}})'>toto</div>

The goal is to append a new div in response to clicking the button, creating a sequence like this:

First click results in:

<div id="box"><div ng-click='updateTypeZone(1)'></div></div>

Second click results in:

<div id="box"><div ng-click='updateTypeZone(1)'></div><div ng-click='updateTypeZone(2)'></div></div>

And so on...

If you have any insights on resolving this issue, please let me know.

Answer №1

Keep in mind that your perspective is just a reflection of your controller. Instead of manually injecting the html into the dom, you can easily add it to your template using ng-repeat and make adjustments to the controller.

var app = angular.module("app", []);

app.controller('myController', function($scope) {
  $scope.count = 0;
  $scope.add = function() {
    $scope.count += 1;
  };
  $scope.range = function() {
    var input = [];
    for (var i = 0; i <= $scope.count; i++) {
      input.push(i);
    }
    return input;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app" ng-controller="myController">
  <button ng-click="add()">add</button>
  <ul>
    <li ng-repeat="n in range()">listing {{ n }}</li>
  </ul>
</div>

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

Minimize the entire project by compressing the .css, .js, and .html files

After recently incorporating Grunt into my workflow, I was thrilled with how it streamlined the process of minifying/concatenating .css files and minifying/uglify/concatenating .js files. With Grunt watch and express, I was able to automate compiling and ...

Notify immediately if there is any clicking activity detected within a designated div container

I am looking to trigger an alert when a specific div is clicked. Here is the scenario: <div class="container"> <div class="header"> <h1>Headline<h1> </div> <div class="productbox"></div> </div> I have succ ...

Best JavaScript approach for discovering time-dependent occurrences

In my Javascript code, I am working with an array of objects that have event start and end times stored as milliseconds. The current search algorithm in our codebase loops through the array until finding an event that contains a specific moment: // Lookin ...

Look through an array to find a particular string and send the result back to an AngularJS view

Currently, I am faced with the task of searching through a JSON output in my code to locate a specific string (for instance 'name_col_lbl') and then extracting its corresponding value ('Name' in this example) for AngularJS to display in ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Embedding a thread in an HTML document (Difficult task)

I'm currently working on a method to achieve the following task: Embedding a specific string (such as "TEST") into the content of an HTML page, after every certain number of words (let's say 10). The challenge here is ensuring that the word count ...

Angular UI-grid with Treeview功能

I'm facing an issue while trying to implement a tree view in angular ui-grid. The error message I keep encountering is related to the template not being found for the treeViewRowHeader. In my case, there seems to be no existing template and there&apo ...

Using an external JavaScript file instead of embedding the code directly into your HTML file when working with Express can

I am facing a dilemma while trying to deploy a simple express application. I have encountered a strange issue that has me stumped. The problem arises when I attempt to use an external JavaScript file instead of inline script in the HTML file – this resul ...

Using Javascript to make a nested JSON api request that includes several query parameters

I am currently working on creating an API for my upcoming website, but I am facing difficulty in obtaining multiple query results using the same URL in an express app. Sample data: var data = [{ articles : [{ id : '0', url : ...

JavaScript functions may become unresponsive following ajax loading with tables

I have a table that is automatically generated by a database using PHP with four rows. The last row (4) has a button that triggers the function below, and this is repeated for every line. After clicking the button, the script sends a request to update the ...

AngularJS: Transforming form field inputs into JSON format

I am curious about how I could create a function (either a directive or controller) that can convert all of my form inputs into JSON, including their current values. The JSON format I have in mind is something like this: { fields: [ {fi ...

Using Handlebars to incorporate altered ajax information into a template

Currently, I am exploring ways to utilize manipulated data from an ajax request in conjunction with Handlebars. Within my database, the data is stored as an object like so: {"1 year":"$4.95", "2 years":"$3.95"} My objective now is to make use of this d ...

'Angular package is not found' error appears when executing 'meteor test' command

As I attempt to develop tests for my Meteor application using practicalmeteor:mocha, I encounter an issue with the message angular package is missing displaying when the page loads. The command I utilize to initiate the process is: meteor test --driver-p ...

Obtain the parameter fetching identical identifier

When I click on a search result on the left, I want it to load in the right div without refreshing the page or opening a new one. The search generates three results with pagination. However, no matter which result I click, the same ID loads. Can anyone spo ...

Utilizing objects as tags within the Form Tags component in Bootstrap Vue

Let's break down the following code snippet from the documentation: <template> <div> <b-form-tags v-model="value" no-outer-focus class="mb-2"> <template v-slot="{ tags, inputAttrs, inputHandlers, addTag, removeTag }"> ...

Implement the Page Object Pattern with promise in Protractor for efficient automation testing

I am working with two classes named: LayerWrapper Layer These classes are utilized as page objects. I am looking to revamp the following method: export class LayerPanel { public static layers = element.all(by.automationId('layer')); ...

Trouble arises when trying to load angular ui-bootstrap using require.js unless I change the name to ui.bootstrap

Code Overview: main.js: require.config({ paths: { 'uiBootstrap': '../lib/bootstrap/angular-bootstrap/ui-bootstrap-tpls.min' }, shim: {***}, priority: ['angular'], deps: ...

What should I do to resolve the issue of ajax failing to update data randomly?

This script is designed to take the value entered into an HTML form and send it to the ../Resources/BugReport.php file. The data is then inserted into a database in that file, and the table in the ../Resources/BugDisplay.php file displays the information f ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...