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

AngularJS:指令无法访问隔离作用域对象,第1张

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

问题是:那时angular 尚未更新其绑定

您不应该这样访问变量,请尝试使用angular js绑定机制将其绑定到 视图 (例如,使用$ watch)。绑定到父作用域变量意味着您是
被动的
,只需侦听更改并更新 其他变量 视图即可 。这就是我们应该使用角度的方式。

如果您仍然需要访问它。您可以使用$
超时尝试解决方法

$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,在这种情况下,您无需广播事件。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4988471.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存