我试图在我的指令中使用Isolate作用域放置一些默认值.基本上,当我的指令被绑定时,我需要使用scope对象进行一些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?还有另一个处理这个问题的人吗?
问题是:那时角度还没有更新它的绑定.
原文链接:https://www.f2er.com/angularjs/140401.html你不应该访问这样的变量,尝试使用角度js绑定机制来绑定它来查看(例如使用$watch).绑定到父范围变量意味着您是被动的,只是监听更改并更新其他变量或视图.这就是我们应该如何工作的角度.
如果您仍然需要访问它.您可以使用$timeout尝试解决方法
$scope.setDefaults = function() { $timeout(function () { alert(JSON.stringify($scope.appSubs)); //Coming as undefined },0); };
最好使用$watch
angular.module('ctrl',[]).controller('TempCtrl',function ($scope,$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,attrs) { },controller: function ($scope,$timeout) { $scope.$watch("appSubs",function(newValue,OldValue,scope){ if (newValue){ alert(JSON.stringify(newValue)); } }); },template: "<div>{{appSubs}}</div>" }; });
通过使用$watch,您不需要在这种情况下广播您的活动.