AngularJS : Directive not able to access isolate scope objects

后端 未结 2 491
谎友^
谎友^ 2021-01-02 07:30

I am trying to put some default values in my directive with Isolate scope. Basically, I need to do some DOM manipulations using the scope object when my directive is bound.

相关标签:
2条回答
  • 2021-01-02 08:00

    The problem is: at that time angular does not update its bindings yet.

    You should not access your variables like this, try to use angular js binding mechanism to bind it to view (by using $watch for example). Binding to parent scope variables means you're passive, just listen for changes and update other variables or your view. That's how we should work with angular.

    If you still need to access it. You could try a workaround using $timeout

    $scope.setDefaults = function() {
        $timeout(function () {
            alert(JSON.stringify($scope.appSubs)); //Coming as undefined  
        },0);          
    };
    

    DEMO

    It's better to use $watch

     angular.module('ctrl', []).controller('TempCtrl', function ($scope, $location, $rootScope) {
             $scope.appSubscriptions = "Subscriptions";
             $scope.appObj = "Objs";
             $scope.showAppEditWindow = function () {
                 //Binding the directive isolate scope objects with parent scope objects
                 $scope.asAppObj = $scope.appObj;
                 $scope.asAppSubs = $scope.appSubscriptions;
    
             };
         });
    
         angular.module('ctrl').directive('tempDirective', function () {
             return {
                 restrict: 'E',
                 replace: true,
                 scope: {
                     appObj: '=asAppObj',
                     appSubs: '=asAppSubs'
                 },
                 link: function (scope, element, attrs) {
    
                 },
                 controller: function ($scope, $timeout) {
                     $scope.$watch("appSubs",function(newValue,OldValue,scope){
                         if (newValue){ 
                             alert(JSON.stringify(newValue)); 
                         }
                     });
                 },
                 template: "<div>{{appSubs}}</div>"
             };
         });
    

    DEMO

    By using $watch, you don't need to broadcast your event in this case.

    0 讨论(0)
  • 2021-01-02 08:17

    Most likely the isolated scope variable is not available when the directive's controller first instantiates but probably its available when you need it for a following event such as: within a function bound to an ng-click

    its just a race condition and the object doesn't arrive exactly when directive's controller loads

    0 讨论(0)
提交回复
热议问题