logo
down
shadow

Pass variable to AngularJS directive without isolated scope


Pass variable to AngularJS directive without isolated scope

By : Charles Sparkley
Date : November 22 2020, 01:01 AM
will help you I am learning AngularJS directive, and one thing I want to do is to pass some variable $scope.message in the parent scope (a scope of a controller), and I want it to be renamed to param inside the directive alert. I can do this with an isolated scope: , Modify your toast directive:
code :
.directive("toast", function(){
    return{
        restrict: "A",
        link: function(scope, elem, attrs){
            var param = scope.$eval(attrs.param);
            console.log(param)
        }
    }
})


Share : facebook icon twitter icon
AngularJS isolated scope variable in directive not being set

AngularJS isolated scope variable in directive not being set


By : Juan Pedro
Date : March 29 2020, 07:55 AM
help you fix your problem When you use the @ binding for the isolate scope, it only gives you the string value of the attribute, it does not evaluate it as an expression. I made a couple changes to your Fiddle to make it work. Needed an ng-app added, change the attribute name on your directive (camel case doesn't work in the template for attribute names) and put double curlies around your expression so it will get evaluated. I also added an input element so you can see the data get updated, you don't need a watch in this situation. Here is the result:
http://jsfiddle.net/pkqUn/3/
code :
<div ng-app="myApp" ng-controller="myCtrl">  
    <input ng-model="currentLog.RelationshipId"></input>
      <div>
          *<div data-personselect="" data-relationship-id="{{ currentLog.RelationshipId }}"></div>*
      </div>
</div>

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

myApp.directive('personselect', function() {
    return {
        template: '<span> test {{ relationshipId }}<span>',
            restrict: 'A',
            replace: true,
            scope: {
                relationshipId: '@'
            }
        };
});

function myCtrl($scope){
    $scope.currentLog = {};
    $scope.currentLog.RelationshipId = 123;
}
angularjs, how to pass parent scope isolated variable to a directive, and watch the variable value

angularjs, how to pass parent scope isolated variable to a directive, and watch the variable value


By : Dipali
Date : March 29 2020, 07:55 AM
help you fix your problem The watch needs to include an additional boolean true value on the watch to perform a deep comparison.
code :
     $scope.$watch('search', (o, n) => {

        // this watch only get's called once, and never again.

        this.$log.log(`watch called ${JSON.stringify(o)} :: ${JSON.stringify(n)}`);
        if (n) {
            this.$log.log(`watch updating ${JSON.stringify(n)}`);                    

            // it turns out the below code is not necessary, but
            // it only gets' called once, even when the value changes.
            $scope.searchTextBox = n;
        }
    }, true); // the true is necessary
angularJS attribute based directive - pass isolated scope

angularJS attribute based directive - pass isolated scope


By : Manilyn Bordeos
Date : March 29 2020, 07:55 AM
it should still fix some issue You can do this in exactly the same way as you did with element directive, i.e. attach further attributes that pass in the properties to the isolated scope.
HTML:
code :
<div greeting-directive my-greeting="'hello'" greet-who="'world'"></div>
angular.module("myApp").directive("greetingDirective", function(){
    return {
        restrict: 'A',
        scope: {
            myGreeting: "=",
            greetWho : "=" 
        },
        template: '<p>{{ myGreeting }}, {{ greetWho }}</p>'
    }
});
AngularJS - Pass value from isolated scope directive to another element

AngularJS - Pass value from isolated scope directive to another element


By : Achala HR
Date : March 29 2020, 07:55 AM
To fix the issue you can do Usually it is a better practice to make your data to flow in one direction. Therefore, the owner of the dataLoading variable should be the common parent of the 2 components.
If the logic of that boolean should be inside user-login component, you can pass it an callback (via &), then user-login component will call it when ever it starts to fetch the data, then the parent will change the value of that boolean, and propagate it to the relevant children.
code :
const app = angular.module('app', []);

app.directive('parentComponent', function() {
    return {
      controllerAs: 'parentVM',
      controller: function() {
        this.isLoading = false;
        this.onLogin = () => {
          this.isLoading = true;
        }
      },
      template: '<div><child on-login="parentVM.onLogin()"></child><other-child is-loading="parentVM.isLoading"></other-child></div>'
    };
  })
  .directive('otherChild', function() {
    return {
      scope: {
        localLoading: '=isLoading'
      },
      template: '<div ng-class="{\'is-loading\':localLoading}">{{localLoading? \'Loading...\': \'\'}}</div>'
    }
  })
  .directive('child', function() {
    return {
      scope: {
        onLogin: '&'
      },
      template: '<button ng-click="onLogin()">Login</button>'
    };
  })
.is-loading {
  background-color: rgba(0, 200, 0, 0.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>

<div ng-app="app">
  <parent-component></parent-component>
</div>
angularjs how to access controller $scope variable in directive isolated scope

angularjs how to access controller $scope variable in directive isolated scope


By : Billy Saputra
Date : March 29 2020, 07:55 AM
it helps some times You need to add a function expression to both of your directives' isolate scopes in order to properly call a function in your parent scope. Taking your original code, it should look something like this:
code :
var app = angular.module('plunker', []);

app.directive('collection', function () {       
    return {
        restrict: "E",
        //replace: true, <- this is deprecated and should no longer be used
        scope: {
            collection: '=',
            onMemberClick: '&'
        },      
        template: "<ul><member ng-repeat='member in collection' member='member' on-click='onMemberClick()'></member></ul>"         
    }
})

app.directive('member', function ($compile) {
    return {
        restrict: "E",
        //replace: true, <- this is deprecated and should no longer be used
        scope: {
            member: '=', 
            onClick : '&'
        },
        template: "<li><span ng-click='onClick()'>{{member.NodeName}}</span></li>"       
    }
});
<body ng-controller="MainCtrl">
  <div id="TestContainer" class="TestContainer" ng-init=Intialfunc()>
    <collection collection='testdata' on-member-click='ShowDetailsCtrlFunc ()'>{{testdata}}</collection>             
  </div>
</body>
var app = angular.module('plunker', []);

app.directive('collection', function () {       
    return {
        restrict: "E",
        scope: {
            collection: '=',
            onMemberClick: '&'
        },      
        template: "<ul><member ng-repeat='member in collection' member='member' on-click='onMemberClick({member: member})'></member></ul>"         
    }
})

app.directive('member', function ($compile) {
    return {
        restrict: "E",
        scope: {
            member: '=', 
            onClick : '&'
        },
        template: "<li><span ng-click='onClick({member: member})'>{{member.NodeName}}</span></li>"       
    }
});
<body ng-controller="MainCtrl">
  <div id="TestContainer" class="TestContainer" ng-init=Intialfunc()>
    <collection collection='testdata' on-member-click='ShowDetailsCtrlFunc (member)'>{{testdata}}</collection>             
  </div>
</body>
app.controller('MainCtrl', function ($scope) {      

    $scope.Intialfunc = function() { 
        $scope.testdata = []
        var myjsondata = JSON.parse('{ "NodeName": "Parent", "children": [ { "NodeName": "mychild", "children": [ { "NodeName": "chld1", "children": [] } ] } ] }');
        $scope.testdata.push(myjsondata);
            console.log($scope.testdata) //This one is showing
        }       

    $scope.ShowDetailsCtrlFunc = function(member) {
            console.log("In show details function");
            console.log(member);       
      };
});
Related Posts Related Posts :
  • Open $modal from the service and pass variables to the controller
  • ngClick evaluated against scope instead of isolateScope
  • onEnter and onExit are not called when state is left/activated in angularjs ui router
  • Shared client & server modules with angularjs and pongular
  • Getting the angular app to run when using protractor
  • Angularjs: create a link for download different types of file
  • AngularJS: On Change of Parent DropDown Option Also Changes the Dependant Drop Down Options Associated with Other Parent
  • Angular HTML5 mode, Wordpress, Rewrites, Apache and You
  • Using angular js form validations in <form:input> tag
  • AngularJS call common functions in a directive template
  • AngularJS Promise resolved incorrectly
  • properly clearing whole AngularJS ui-grid chart
  • Can not figure out how to store $rootScope in angular.bootstrap
  • animate.css animation within angularjs 1.3 using ngAnimate gives different animations in Firefox
  • Auth0 IE Issue: Unable to get property 'frames' of undefined or null reference
  • Am I misusing directives with too much logic?
  • Use an Angular JS value as a parameter of TWIG "path" function in Symfony 2
  • multiple function on ng-click angularjs
  • Converting $.ajax call to $http call in angular 404 error
  • Angularjs templateUrl file location not found
  • How to execute the function after change page in angularjs?
  • OAuth, Custom Login, or Both
  • Angular Directive: Isolate Scope & Transclude is true, but HTML in the directive needs to continue to bind to parent
  • Compare objects in angularjs
  • Combine "Checkbox" & "Avatar" in an Ionic Framework List
  • Issue with the Angular UI router when inheriting from a parent state
  • Is there a way to initialize an Angular Service without DI into controller
  • Why is a parent controller's $scope not accessible from a (child) directive?
  • How to get back button in Ion-tabs page
  • AngularJS bind class attribute to model
  • How can I get AngularJS ui-router to respond correctly to a browser page refresh?
  • Angular validation does not work
  • Breez Create Complex Entities
  • Drag and drop using protractor in dthmlx component
  • In Angular JS, what is the default 'cache' value that is used when sending request with $http service?
  • How to change placeholder for single textbox in angular?
  • $ is not defined - jquery angular mixing
  • CORS issue angularjs and spring security
  • Angularjs cannot select last item in dropdown the first time
  • Angularjs - $watch issue
  • On change radio button to no the span should hide in angular
  • Creating a wordcloud generator in Angularjs
  • Angular UI Bootstrap collapse - whats wrong?
  • AngularJS after redirect from app to app, the default page is not loading
  • Why does my scope update my factory and my factory update my scope when it should not?
  • AngularJS testing $httpBackend.whenGET().respond() not working with number as parameter
  • Setting up Login in Angular App
  • Retrieve value that is stored in db and display in select box using angularjs and laravel
  • Binding nested array in Angular view
  • Using filter with geojson, right direction?
  • Angularjs : mistake with $q
  • Apply logic to every element in an ng-repeat upon ng-click (AngularJS)
  • Directive within a directive fails to bind event
  • Header with image with ionic framework
  • What is the correct way to validate all form fields on submit when using ng-repeat for dynamic form?
  • Unit testing angular apps without launching a browser
  • Update jQuery Datepicker UI without Changing the Associated Input
  • angular directives ng-if replace: true
  • Angular default not applying without <div ng-view>
  • Issue with accessing css from build file
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org