Error in AngularJS - filterProvider not recognized

When the two script statements below are combined, they cause an error: "Error: [$injector:unpr] Unknown provider: searchNameFilterProvider <- searchNameFilter." Can someone explain why this happens?

1st segment

Find Person: <input type="text" ng-model="myName">
    <ul ng-init="people = ['Diarmuid','Aine','Dave','Declan']">
        <li ng-repeat="person in people | filter:myName">{{ person | searchName}}</li>
    </ul>

    <script>
        var app = angular.module('myApp',[]);
        app.filter('searchName',function(){
            return function (input){
                return input + '!';
            }
        })
    </script>

2nd segment

<div ng-controller="myCtrl">
    <button ng-click="myFunc()">Hello World Button</button>
</div>

<script>

    var app = angular.module('myApp',[]);
    app.controller('myCtrl',function ($scope) {

        $scope.myFunc = function () {
           console.log('Hello world!');
        };
    });

</script>

Answer №1

<div ng-app="myApp">
    <script src="Scripts/Angular.js" type="text/javascript"></script>
    Displaying Names:
    <input type="text" ng-model="myName">
   <ul ng-init="people = ['John','Emily','Michael','Sarah']">
        <li ng-repeat="person in people | filter:myName">{{ person | modifyName}}</li>
    </ul>
   <script>
       var app = angular.module('myApp', []);
       app.filter('modifyName', function () {
           return function (input) {
                return input + '!';
           };
       });
   </script>
  <div ng-controller="myCtrl">
        <button ng-click="outputMessage()">
          Click Me Button</button>
   </div>
   <script>

    var app = angular.module('myApp');
    app.controller('myCtrl', function ($scope) {

        $scope.outputMessage = function () {
            console.log('Button clicked!');
        };
    });

</script>

Answer №2

It is important to note that there should only be a single module initialization in your code. Rectifying the repeated initialization will resolve the issue.

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

The AngularJS documentation explains this concept clearly.

"Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module"

You can find more information about modules here: AngularJS Modules

var app = angular.module('myApp', []);
app.filter('searchName', function() {
  return function(input) {
    return input + '!';
  }
});

app.controller('myCtrl', function($scope) {

  $scope.myFunc = function() {
    console.log('Hello world!');
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  Find Person:
  <input type="text" ng-model="myName">
  <ul ng-init="people = ['Diarmuid','Aine','Dave','Declan']">
    <li ng-repeat="person in people | filter:myName">{{ person | searchName}}</li>
  </ul>

  <div ng-controller="myCtrl">
    <button ng-click="myFunc()">Hello World Button</button>
  </div>
</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

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Issues related to ng-model within a dropdown list

Currently, I am facing an issue with retrieving the selected value from a select element using ng-model. Even though the value is displayed correctly on the application page, it remains at the initial value in the app controller. Despite my efforts to find ...

I am looking to incorporate automatic scrolling functionality into my RSS Feed

I'm in the process of developing an RSS feed for my website. My expertise in JS/jQuery is limited, so any assistance would be greatly appreciated. After utilizing Google's Feed API and creating my own RSS Reader Widget, I realized that it lacked ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...

Assign a specific index value from a PHP array to a JavaScript variable

Having a large PHP array with 649 indexes, I am looking to assign a specific index value to a JavaScript variable based on another variable. Is there a way to achieve this without loading the entire PHP array onto the client side for speed and security rea ...

The TinyMCE editor's input box lost focus while on a popup dialog

Whenever I attempt to access the TinyMCE editor in a dialog box popup and click on "Insert link", the "Insert link" dialog box pops up but I can't type anything into the text field. I suspect that the issue may stem from having a dialog box open with ...

Even after setting the handler to return false, Angular continues to submit the form

In the following scenario, I have encountered an issue: Here is the HTML template snippet: <form [action]='endpoint' method="post" target="my_iframe" #confirmForm (ngSubmit)="submitConfirmation()"> <button type="submit" (click)="conf ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

Serve an image in Node.js from a location outside of the public folder

Is there a way to display an image that is located outside of the public folder in my webroot? Here is my directory structure: Webroot --core ----views ----public <- Stylesheets and other images are stored here ------index.ejs <- I want to display f ...

Tips for keeping the main section from scrolling while scrolling through the side navigation

Within my Angular application, I have implemented a sidenav and a main section. My desired behavior is to prevent any scrolling in the main section while I am scrolling in the sidenav, similar to the functionality seen on the Angular Material Design docume ...

Is there a workaround using jQuery to enable CSS3 functionality across all browsers?

Is there a way in jQuery to make all browsers act as if they have CSS3 capabilities? ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

The timepicker is set to increment by 30-minute intervals, however, I would like the last time option to be 11:

I am currently using a timepicker plugin and am trying to set the last available time option to be 11:59pm. Despite setting the maxTime attribute in my code, the output does not reflect this change. Any suggestions on how to achieve this would be highly ap ...

What could be causing Mathjax to generate multiple copies?

I have integrated MathJax into my application to render MathML. The code snippet below is used to ensure that the MathML is typeset properly: $rootScope.$watch(function() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); return true; }); However, I ...

Best practices for storing non-reactive and static data in a Vue application

Welcome to the community! I'm excited to ask my first question here on StackOverflow. I am currently working with vue.js-v2 and webpack. My goal is to ensure that data remains immutable for child components, which are loaded through the vue-router. T ...

Customizing the appearance of Jquery UI Accordion Headers

Trying to integrate the JQuery UI accordion into my JQuery UI modal dialog has been causing some alignment issues. Despite following code examples found online, such as http://jsfiddle.net/eKb8J/, I suspect that the problem lies in CSS styling. My setup i ...

JavaScript class with callback function commonly used

I am looking to create a JavaScript class that can register multiple functions to run with a common callback. Each registered function should run asynchronously, and once they have all completed, the specified callback function should be executed. In addi ...

Tips for retrieving the user-input value from an HTML text field

Exploring the world of JS, I set out to create a basic calculator after just one week of lessons. However, I hit a roadblock when trying to extract user-input values from my HTML text fields. Here's a snippet of my html: <div class="conta ...

Can a custom directive with dynamic behavior be crafted in AngularJS?

Allow me to begin by explaining my intentions with broken-pseudocode: // controllers.js angular.module('myApp.controllers', []). controller('MyCtrl1', [function() { var template = '<div my-directive></div>' ...