0

的呼叫控制器方法我有一个按钮可以改变“活动”状态。首先,它加载从服务器状态来自指令

<button active="data.active" ng-click="changeStatus()"></button> 

指令代码:

app.directive('active', function() { 
    return { 
    restrict: 'A', 
    templateUrl: 'whatever.html', 
    scope: { 
     active: '=' 
    }, 
    link: function($scope, elem, attrs) { 
     $scope.changeStatus = function() { 
      // Actually I'm doing this, it works fine 
      var value = !$scope.active; 

      $scope.$parent.MethodWhoChangesState(value, function(response) { 
       // I need to change the button state here 
      }); 
     } 
    } 
    } 
}) 

它的工作原理,但我觉得我不尊重“角的规则” ......

有没有更好的方法?

+0

您应该通过属性传给你的函数,并用它绑定到范围'&' – jcubic

+0

总是好的评估如果你真的需要一个孤立的范围。如果没有,你的指示将已经在父范围 – charlietfl

+0

@charlietfl如果他不创建新的范围与attr biding,那么他将需要自己双倍绑定。 – jcubic

回答

0

通常情况下,您只需在您的点击处理程序中更新$ scope变量。如果你需要处理的情况下,当“有效”状态的改变,你可以设置$表:

app.directive('active', function() { 
    return { 
    restrict: 'A', 
    templateUrl: 'whatever.html', 
    scope: { 
     active: '=' 
    }, 
    link: function($scope, elem, attrs) { 

     // if you need to run custom code whenever the 'active' state changes 
     // you can set up a $watch 
     $scope.$watch('active', function(isActive) { 
       if(isActive) { 
        ... 
       } 
       else { 
        ... 
       } 
     }); 

     $scope.changeStatus = function() { 

      $scope.active = !$scope.active; 
     } 
    } 
    } 
}) 
+0

我需要调用$ parent作用域的函数,另外,如果我把这个调用放在$ watch中,我认为它会在第一次渲染指令时执行。 – Ulrira