从指令调用控制器方法

时间:2014-07-04 19:49:18

标签: angularjs angularjs-directive angularjs-scope angularjs-controller

我有一个按钮可以更改"活动"州。首先,它从服务器加载状态

<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
            });
        }
    }
  }
})

它有效,但我认为我不尊重&#34;棱角分明的规则&#34; ......

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

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

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;
        }
    }
  }
})
相关问题