AngularJS:指令无法访问隔离作用域对象

9
我可以帮助您翻译以下内容,这是关于IT技术的:

我正在尝试在Isolate作用域中设定一些默认值。基本上,当我的指令绑定时,我需要使用作用域对象进行一些DOM操作。以下是我的代码:

控制器:

angular.module('ctrl').controller('TempCtrl', function($scope, $location, $window, $timeout, RestService, CommonSerivce) {

$scope.showAppEditWindow = function() {
    //Binding the directive isolate scope objects with parent scope objects
    $scope.asAppObj = $scope.appObj;
    $scope.asAppSubs = $scope.appSubscriptions;

    //Making Initial Settings
    CommonSerivce.broadcastFunction('doDirectiveBroadcast', "");
};

服务:

angular.module('Services').factory('CommonSerivce', function ($rootScope) {
return {       
    broadcastFunction: function(listener, args) {
        $rootScope.$broadcast(listener, args);
    }
};

指令:

angular.module('directives').directive('tempDirective', function() {
return {
    restrict : 'E',
    scope:{
        appObj:'=asAppObj',
        appSubs: '=asAppSubs'
    },
    link : function(scope, element, attrs) {},
    controller : function ($scope,Services,CommonSerivce) {         
        //Broadcast Listener 
        $scope.$on('doDirectiveBroadcast', function (event, args) {
            $scope.setDefaults();
        });

        $scope.setDefaults = function() {
            //Setting Default Value
            alert(JSON.stringify($scope.appSubs)); //Coming as undefined            
        };
    },
    templateUrl:"../template.html"
    };
});

自定义指令元素:

<temp-directive as-app-obj="asAppObj" as-app-subs="asAppSubs" />

现在的问题是,在指令内部的默认方法中尝试访问隔离作用域时,我得到了未定义的值,而数据已经被绑定到DOM上。如何在广播监听器中访问隔离作用域并修改指令模板HTML?还有其他处理这个问题的方法吗?


你能创建一个 Fiddle 吗? - AlwaysALearner
2个回答

18

问题是:此时angular还未更新其绑定。

您不应该像这样访问变量,尝试使用AngularJS的绑定机制将其绑定到视图(例如使用$watch)。绑定到父作用域变量意味着您是被动的,只需监听更改并更新其他变量或您的视图。这就是我们应该如何处理Angular的方式。

如果仍需要访问它,可以尝试使用$timeout的解决方法。

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

演示

最好使用 $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>"
         };
     });

演示

使用$watch,在此情况下,您无需广播事件。


3
你应该使用 $watch 来解决这个问题。请查看类似问题的网站 https://dev59.com/KXfZa4cB1Zd3GeqPSoaW#19204970。 - Khanh TO
1
@Khank:这样更好 :). 为什么“watch”定义应该添加在“link”内部?我测试过,在“controller”下也可以工作。 - Akhilesh Aggarwal
@Akhilesh Aggarwal:在你的情况下,我认为你应该在controller中使用$watch。因为控制器应该包含你的逻辑,而链接函数只关心模型和视图之间的动态连接。 - Khanh TO
2
根据AngularJS的指令文档(https://docs.angularjs.org/guide/directive):“最佳实践:当您想要向其他指令公开API时,请使用控制器。否则,请使用链接。” - Seth Flowers

1
很可能当指令控制器首次实例化时,隔离作用域变量不可用,但可能在后续事件中可用,例如:在绑定到ng-click的函数内部。这只是一种竞争条件,对象并不会恰好在指令控制器加载时到达。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接