What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() {
  return {
    scope: {},
    bindToController: {
      count: '='
    },
    controller: function () {
      function increaseCount() {
        this.count++;
      }
      function decreaseCount() {
        this.count--;
      }
      this.increaseCount = increaseCount;
      this.decreaseCount = decreaseCount;
    },
    controllerAs: 'counter',
    template: [
      '<div class="todo">',
        '<input type="text" ng-model="counter.count">',
        '<button type="button" ng-click="counter.decreaseCount();">-</button>',
        '<button type="button" ng-click="counter.increaseCount();">+</button>',
      '</div>'
    ].join('')
  };
});

`

I attempted to use $apply in toddmotto's jsfiddle for reference, but it did not work as expected.

Any assistance would be greatly valued.

Answer №1

If you're unsure about how to handle those methods, it's important to remember that injecting $scope into the directive controller is necessary in order to utilize them effectively.

Just like with a typical angular.module('').controller

controller: function ($scope) {
      var vm = this;
      ...

     $scope.$watch(function(){
          return vm.someProp;
      }, function(newVal,oldVal){
          // watch code
     });
    ....

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

Retrieve a JSON object from a Knockout observable array using the object's ID

I'm struggling to find examples of ko.observablearrays that deal with complex JSON objects instead of simple strings. I have an observable array containing a large JSON object with several properties, and I need to retrieve a specific object based on ...

Why is my update with upsert: true not working in Express and Mongoose?

var logs = [{ mobilenumber: '1', ref: 3, points: 1000, ctype: 'mycredit', entry: 'sdfsdf', entry: 0 }, { mobilenumber: '1', ref: 6, points: 2000, ctype: 'mycredit', ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Avoiding Duplicate Form Submissions Without JavaScript

Currently, I am working on a project where I am implementing the MVC pattern. Upon successful submission of a form, I redirect the user and display a flash message indicating success using session data. Users face no issues when using the back button or re ...

Extract information from an external website using AJAX in Laravel

On my cart page, I utilize ajax to retrieve destination information from the user and provide them with shipping options to calculate their shipping cost. While everything is functioning properly, one issue remains: I am unsure of how to iterate through t ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

How does Code Sandbox, an online in-browser code editor, manage file storage within the browser?

What are the ways in which Code Sandbox and StackBlitz, as online in-browser code editors, store files within the browser? ...

Enhance your message inbox experience with jQuery/Javascript features inspired by Gmail, including the ability to select all messages with a checkbox and

It is truly satisfying to be here working on developing a private message inbox for my website, especially after successfully implementing a complete user signup/login and activation system. A few months ago, I never believed I had enough patience to grasp ...

Interacting with the DOM of an iFrame from a separate window using Javascript

My main webpage is hosted on "DomainA" and it contains an iFrame sourced from "DomainB". Within this iFrame, there is a click event that opens a new window, also sourced from "DomainB". I am attempting to update an input field within the iFrame from the n ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Why is it that the window object in JavaScript lacks this key, while the console has it?

let myFunction = function declareFunc() { console.log(this); // window console.log(this.declareFunc); // undefined console.log(declareFunc); // function body } console.log(this) // window myFunction(); I understand that the this keyword in a functio ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

I am encountering an issue where I am sending an AJAX request to a PHP file with the datatype set as JSONP, but I

When I click on the submit button, I am sending a variable to sendmail.php. However, PHP is showing that 'contactname' is undefined. Why is this happening? Here is the code snippet: var name = document.getElementById('stream_cotactname&apo ...

Error encountered: MongoDB cast exception - nested subdocument

Check out this schema design: var messageSchema = new Schema({ receivers: [User], message: String, owner: { type: Schema.Types.ObjectId, ref: 'User' } }); var userSchema = new Schema({ name: String, photo: String }); var in ...

Tips on changing the default value of a Material UI prop method in React JS

Currently, I'm utilizing React JS and I've brought in a component from Material UI known as (https://material-ui.com/api/table-pagination/). My goal is to customize the Default labelDisplayedRows that looks like this: ({ from, to, count }) => ...

Interfacing with Ajax to dispatch information to a PHP script

Hello, I'm currently working on implementing Ajax in my web application. However, I've encountered a small issue. I'm attempting to check if a username has already been registered by controlling a form. The problem arises when my JavaScript ...

Issue with Vue3 Button - property error not defined

I'm currently facing an issue with a button that isn't functioning as expected in the screenshot provided. I'm hopeful that someone can assist me with this. Button functionality The button itself is not clickable, but I am able to submit t ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Tips for integrating tooltips in a dynamic highcharts chart

This image shows the desired final output View Highcharts here and I am looking to merge the date and stock value in a single tooltip, how can this be achieved? highcharts ...