The $watch feature in AngularJS does not function properly within a directive when a controller is used to update data

I created a custom directive and also have a controller to bind data to the directive.

The data is retrieved from the server and bound to the directive. However, I noticed that the data in the directive on the page does not update when I change the scope variable.

Below is my code:

Directive:

angular.module('MyApp')
.directive('stats',function() {
    return {
    templateUrl:'scripts/directives/dashboard/stats/stats.html',
    restrict:'E',
    replace:true,
    scope: {
    'comments': '@',
    'number': '@',
    'name': '@',
    'colour': '@',
    'details':'@',
    'type':'@',
    'goto':'@'
    },
  link : function($scope,element,attr){
    $scope.$watch('number', function(oldValue,newValue) {
           console.log(attr);  
        }, true);
  }

}
});

Directive Template:

<div class="col-lg-3 col-md-6">
<div class="panel panel-{{colour}}">
    <div class="panel-heading">
        <div class="row">
            <div class="col-xs-3">
                <i class="fa fa-{{type}} fa-5x"></i>
            </div>
            <div class="col-xs-9 text-right">
                <div class="huge">{{number}}</div>
                <div>{{comments}}</div>
            </div>
        </div>
    </div>
    <a href="{{goto}}">
        <div class="panel-footer">
            <span class="pull-left">View Details</span>
            <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
            <div class="clearfix"></div>
        </div>
    </a>
</div>

Controller:

'use strict';
angular.module('MyApp',['ngResource'])

.controller('MainCtrl', function($scope,$state,MyService) {
    $scope.result = {};
    var names = MyService.get({classtype:'getNames',start:'',end:''},function(){
        $scope.pages = names.data;
        if (typeof($scope.pages[0]) === 'undefined'){
            $scope.selectedItem = 'loading...';
        }else{
            $scope.selectedItem = $scope.pages[0].name;
        }
        var res = MyService.get({classtype:'getLastRes',seriesName:$scope.selectedItem},function(){
            $scope.result = res;
        });

    });
    $scope.dropboxitemselected = function(item){
        $scope.selectedItem = item;
        var result = MyService.get({classtype:'getLastRes',seriesName:item},function(){
            $scope.result = result;
        });
        //$scope.result = {};
    };



});

HTML:

<div class="row" ng-controller="MainCtrl">

    <stats number="{{result.score}}" comments="score" colour="primary" type="heartbeat" goto="#/res/{{result._id}}"></stats>
    <stats number="{{result.totalSize}}" comments="size" colour="primary" type="file-code-o" goto="#/res/{{result._id}}"></stats>
    <stats number="{{result.count}}" comments="count" colour="red" type="file-text" goto="#/res/{{result._id}}"></stats>

</div>

There is a dropdown box on the page which triggers the dropboxitemselected function in the controller to refresh the data in the directive. How can I achieve this?

Answer №1

One possible reason for this issue could be related to scope bindings. It is recommended to use '=' for two-way binding instead of '@'.

scope: {
    'value': '=',
    },

Additionally, make sure to remove the brackets from the value in your HTML code.

<display value="data.result" type="info" status="active" link="#/details/{{data.id}}"></display>

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

Is it possible in HTML to create an "intelligent" overflow effect where text is truncated and replaced with an ellipsis "..." followed by a link to view the full content?

I have a <div> that has a limited size, and I am looking for a way to display multiline text in it. If the text exceeds the available space, I would like to add "..." at the end along with a link to view the full content on another page. Is there a ...

Tips for resolving the issue of a Bootstrap dropdown menu overlapping content in its vicinity

I am trying to position a Bootstrap dropdown button on the right-hand side of the page. The dropdown should cover 100% of the page's width and overlay any content when activated. However, there is a large logo on the left-hand side that I want users t ...

Obtaining the accurate offsetTop and offsetLeft values for an element following a CSS3 rotation

Is there a method to accurately determine the offsetTop and offsetLeft values of an element post-transform rotation? Are there any lesser-known element properties that could be helpful in this scenario? Attached is an image that can provide further clari ...

Utilize getJSON to refresh the JavaScript datetimepicker

I am currently using an api with ajax (getJSON) to append data to a specific div called 'open' on my website. However, I now want to update the static values in my datetime picker script for minTime and maxTime. Here is the code snippet: AJAX ...

Issue with setting and showing the PHP data array within the vue.js variable

I am encountering an issue with transferring an array of data from a PHP session variable to a Vue.js variable Here is how I am trying to assign an array of data to a Vue.js variable: permissions:['<?php echo json_encode($_SESSION['permission ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

JavaScript: A step-by-step guide to extracting the file name and content from a base64 encoded CSV

I have a base64 string that was generated by encoding a csv file, const base64 = 'LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlIjsgZmlsZW5hbWU9ImNoYXJ0T2ZBY2NvdW50LmNzd ...

Pressing the HTML button will reveal the cart details in a fresh display box

I have been working on setting up a button to display the items in the shopping cart. I have successfully created the cart itself, but now I am facing the challenge of creating a button called showYourCart that will reveal a box containing the cart detai ...

Vuelidate allows for validation to occur upon clicking a button, rather than waiting for the field

As I navigate my way through learning vuelidate, everything seems to be going smoothly, except for one thing. I can't figure out how to trigger validation only when the "Submit" button is clicked. Currently, the fields turn red as soon as I start typi ...

Are you experiencing issues with the cipher update when using the crypto library?

When using the crypto module for string encryption and the passed string is not 16 bytes, I expected the cipher.update() function to automatically add padding and create a 16-byte string. However, during debugging, cipher.update returned an empty string. I ...

Can Self-Invoking Functions, Resharper 6.1, and JS Lint all Play Nice Together?

Consider this piece of JavaScript code: MyCompany.MyProduct = {}; (function () { "use strict"; MyCompany.MyProduct.doSomethingAmazing = function () { }; }()); This approach is acceptable and passes Mr Crockford's JavaScript lint. Howe ...

Difficulty sending a parameter to the onClick function of a React Button

I'm struggling with passing parameters to my callback function when clicking a material-ui button. Unfortunately, the following approach is not yielding the expected results. const fetchData = async (param) => { } <Button onClick={fetchData(&a ...

Confused about the meaning of the Unknown Provider: $attrsProvider <- $attrs?

While executing my Karma Unit Tests, I've encountered the following error: Error: [$injector:unpr] Unknown provider: $attrsProvider <- $attrs http://errors.angularjs.org/1.2.16/$injector/unpr?p0=%24attrsProvider%20%3C-%20%24attrs at /h ...

The error thrown by Handsontable is that it cannot locate the modules numbro, moment, pikaday, and ZeroClipboard

I've included handsontable-pro, numbro, moment, pikaday, and ZeroClipboard in my application's dependencies listed within the package.json file, for example: "dependencies": { "numbro": "^1.9.0", "moment": "^2.14.1", ... } I have a ...

How come I am receiving the E11000 error from Mongo when I have not designated any field as unique?

Encountering an issue while attempting to save the second document to MongoDB Atlas. The error message reads as follows: Error:MongoError: E11000 duplicate key error collection: test.orders index: orderId_1 dup key: { orderId: null } Despite having no un ...

Using Ajax with Laravel

Currently, I am attempting to utilize Ajax in Laravel in order to display search results in the "search_results_div" div without requiring the user to navigate away from the page. Unfortunately, I have encountered the following error message: "Column not ...

Attention all controllers summoned from one AngularJS document

Having recently delved into the world of AngularJS and Ionic, I've exhaustively searched for solutions both on this forum and beyond. Despite my efforts, nothing seems to be working. My goal is to create an application with a homepage featuring a ser ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

What is the best way to include bootstrap using webpack?

I am currently building a webapp using Typescript and webpack. I have been able to successfully import some modules by including them in my webpack.config.js file as shown below. However, no matter how many times I attempt it, I cannot seem to import the b ...

What is the best method for securely storing and managing refresh and access tokens within a node.js application?

Currently, I am working with next.js and I am looking for a way to persist an API refresh token without using a database in my application. What would be the recommended practice for storing this token securely so that it can be updated as needed? Storin ...