The Angular factory function runs just once

I have implemented two modules module-1 and module-2 within my Angular application.

Within module-1, I have defined a factory as shown below:

angular.module('ui.campaign.manager').factory('validate',['the',function(the) {
    return {
        validateOwner: function(scope) {
            console.log(scope.campaign);
            if(!scope.campaign.owner) {
                scope.view = true;
                scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
                return false;
            }
            return true;
        }
    };
});

In module-2, there is a controller where the validateOwner function is called upon clicking:

var campaignApp = angular.module('module-2',[ 'module-1']);

campaignApp.controller('campaignDetailController', function($scope, validate) {

    $scope.submitCampaignPage = function(){
        validate.validateOwner($scope);
    }
});
<input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

The problem arises when clicking the Next button multiple times - the validateOwner function is not triggered after the initial click. Could this be due to Angular caching the results?

Answer №1

Remember to pass the function parameter as $scope instead of scope.

Additionally, ensure that you declare scope.campaign as an object in the controller or factory to avoid exceptions when trying to access a property of undefined.

Check out this demo:

angular.module("app",[])
.controller("ctrl",function($scope,validate){
$scope.campaign = {}
  $scope.submitCampaignPage = function(){
    console.log(validate.validateOwner($scope))
 }

}).factory('validate',function() {
  return {
      validateOwner: function(scope) { 
          if(!scope.campaign.owner) {
            scope.view = true;
            scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
            return false;
          }
          return true;
      }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

</div>

Answer №2

Have you experimented with placing the controller and factory on the same module for testing purposes? I recently attempted this approach and found that both the controller and factory functioned perfectly together within the same module.

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

How can I add a different CSS class when the initial CSS class is not present?

i have Implemented Image sprites. Below are some CSS classes for Image sprites: .icon-ONE { background-image: url(../img/spritesheet.png); background-position: -32px 0px; width: 32px; height: 32px; } .icon-TWO { background-image: url(../img/spri ...

Implementing toggleable buttons in the DOM with an Angular directive

Check out this Plunker for reference: https://plnkr.co/edit/gLFw26zoJeaM5qtPjCFg?p=preview I am working with an HTML element <sc-chart type="approved"></sc-chart> that utilizes the scChart directive to display a chart on the webpage. Followin ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Is there a way to eliminate spaces from a string using react-native?

As a user of react-native, I've encountered an issue with inconsistent line breaks when inputting long strings on the screen. For example: https://i.sstatic.net/32RwW.jpg I aim to achieve consistent string wrapping as shown in the image below: htt ...

What is the most efficient way to transfer information from a text box in one form to another in AngularJS?

I am currently using a sample form to send data, and I would like to redirect this data to another page named result.html. Could you please guide me on how to achieve this? The code snippet below shows what I have implemented so far in the main page... ...

Determine whether the current time falls within the specified time slots and check if the day is included in the provided array of days

Listing my Weekly Schedule: weekly_schedule: any[] = [ { id: 0, value: 'Monday' }, { id: 1, value: 'Tuesday' }, { id: 2, value: 'Wednesday' }, { id: 3, value: ...

Tips for handling changing form information with useState?

I am faced with a dilemma - I have a dynamic form with potentially hundreds of input fields, making it impractical to create a state for each one individually. My plan is to use an object with the unique key of each form field, but I could use some guidanc ...

The video rendered with fluent-ffmpeg appears to have an elongated image

I am working on combining an mp3 audio file with a jpg image file to create a new mp4 video. Although I have a functional fluent-ffmpeg command that accomplishes this task, there is an issue where the image gets stretched in the final output video, especia ...

Issues with Navigation and Routing in Ionic and AngularJs are causing trouble

I have recently started learning AngularJs and Ionic, and I am attempting to replicate the functionality from this tutorial to create a simple app. However, all I see is a blank screen with no errors in the console log. index.html <!DOCTYPE html> & ...

The combination of ng-class and ng-click is causing issues and not functioning properly

I'm facing an issue with using ng-class and ng-click together. I am trying to add a class to a div when a button is clicked, but it's not functioning as expected. Here is the code snippet: <header> <div id="headerContainer"> ...

Modify the URL in Browser Detection

Hello, I've been using UAParser to identify which browser is being used. For example, I have a window.location.href of "localhost:8000/" When I reload the page and detect that it's from Chrome, I want it to change to "localhost:8000/#chrome" H ...

Is there a way to prevent an HTML5 video from pausing or stopping when scrolling?

At the top of my page, there's a HTML5 video banner with the autoplay and loop attributes. However, when I start scrolling down, the video stops and doesn't resume when I scroll back up. I want the video to keep playing regardless of the user&apo ...

Is it possible to use an if statement within the .map()

I am seeking guidance on how to incorporate an if statement inside .map() Please refer to the code snippet below for context. Currently, the delete button is disabled when the image is not uploaded by the current user, but my objective is to complet ...

The AngularStrap datepicker remains visible even after the trigger event has blurred in the Safari browser on IOS devices

I'm having an issue with my datepicker disappearing on blur of the trigger event in various browsers like Windows Chrome, Windows Safari, Mac Safari, and Android Chrome, except for IOS Safari. Here is my code: <input class="title-menu-left-input f ...

Retrieving the value of a JavaScript variable from an HTML document using Python

I am looking to extract the value of myJSONObject from an HTML document that includes javascript code with a JSON object. Here is an example snippet: <html> <head> </head> <body> <script type="text/javascript"> ...

What advantages can be gained from using the useNavigation hook to get the navigation prop in React Native?

Currently, I am working on a project where they exclusively use useNavigation() to access the navigation prop, even though it is also available in components prop. The same applies to route - do you see any advantages in this approach? ...

Is there a way for us to determine the time at which the user last took a screenshot or photo?

I am currently developing a website using Django and I have a unique requirement. I need to access the last image that a user has taken on their phone, without the image being shared by anyone else. The photo must be captured by the user's device itse ...

Automated downloading based on operating system recognition

1067/5000 How can I use JavaScript to automatically determine the user's operating system on a webpage and then download the correct installation file? Here is the code I have: HTML <!DOCTYPE html> <html> <body> <iframe id=" ...

Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id. Here is the code snippet I've been working on. Unfortunately, i ...

Tips for incorporating momentjs into TypeScript within AngularJS 1.5

I am looking to integrate the momentJs library into my TypeScript code for Date object operations. However, I need some guidance on how to inject TypeScript in AngularJS, as it differs slightly from JavaScript. angular.module("app") .config(functio ...