问题描述
当我修改控制器controller内的某个变量时,希望指令directive能及时获取变量修改后的值。
app.directive(’popoverMobile’,function(){ return {restrict:'E',transclude:true,scope:true,templateUrl:'tmpl/popover.mobile.tmpl.html',controller:['$scope',function($scope){ $scope.popover_status=false; jQuery.ajax({type:'GET',url:'https://**.***.com/**.htm?tel='+$scope.parents_detail.mobile,dataType:'jsonp',jsonp:'callback',jsonpCallback:'jsonpCallback',success:function(data){ $scope.mobile_info=data;} });}],link:function(scope){ scope.switch_popover=function(val){scope.popover_status=val;scope.$apply(); }},replace:true }});
$scope.parents_detail.mobile 是控制器中的变量;当 $scope.parents_detail.mobile 的值发生改变时,重新请求接口。
问题解答
回答1:$scope.$watch回答2:
AngularJS 的 directive 默认能共享父 scope 中定义的属性,例如在模版中直接使用父 scope 中的对象和属性。通常使用这种直接共享的方式可以实现一些简单的 directive 功能。当你需要创建一个可重复使用的 directive,只是偶尔需要访问或者修改父 scope 的数据,就需要使用隔离 scope。
AngularJS Directive 隔离 Scope 数据交互