2015-11-20 51 views
1

我执行在控制器的手表,当用户切换按钮在未检测指令的变化。我有一个手表内的指令,并正在工作,例如它检测到的范围变量的变化,但如果我有在控制器内的手表不检测

<button toggle-button active-text="Yes" inactive-text="No" ng-model="light.state">Show millions</button><br>

这里是代码:

'use strict'; 
 
angular.module('fiveYearOverview', ['fiveYearOverviewServices', 'fiveYearOverviewDirectives']) 
 
    .controller('fiveYearCtrl', [ 
 
     '$scope', 'reports', 
 
     function ($scope, reports) { 
 

 
      //not working 
 
      $scope.$watch('lightState', function (newValue, oldValue) { 
 
       if (newValue) 
 
        console.log("I see a data change!"); 
 
      }, true); 
 

 
     } 
 
    ]) 
 
    .directive('toggleButton', function() { 
 
     return { 
 
      require: 'ngModel', 
 
      scope: { 
 
       activeText: '@activeText', 
 
       inactiveText: '@inactiveText', 
 
       lightState: '=ngModel' 
 
      }, 
 
      replace: true, 
 
      transclude: true, 
 

 
      template: '<div>' + 
 
       '<span ng-transclude></span> ' + 
 
       '<button class="btn" ng-class="{\'btn-primary\': state.value}" ng-click="state.toggle()">{{activeText}}</button>' + 
 
       '<button class="btn" ng-class="{\'btn-primary\': !state.value}" ng-click="state.toggle()">{{inactiveText}}</button>' + 
 
       '</div>', 
 

 
      link: function postLink(scope) { 
 

 
       scope.lightState = scope.inactiveText; 
 
       scope.state = { 
 
        value: false, 
 
        toggle: function() { 
 
         this.value = !this.value; 
 
         scope.lightState = this.value ? scope.activeText : scope.inactiveText; 
 
         console.log(scope.lightState); 
 

 
         //working 
 
         scope.$watch('lightState', function (newValue, oldValue) { 
 
          if (newValue) 
 
           console.log("I see a data change!"); 
 
         }, true); 
 

 
        } 
 
       }; 
 
      } 
 

 
     } 
 
    });

这是什么我做错了?

回答

2

通过在指令中定义范围,您正在为其创建一个独立的范围。这就是为什么你不能从控制器访问其成员。

0

lightState正在低于fiveYearCtrl的范围内声明,使其无法访问,如概述here

另一种解决方案可能是fiveYearCtrl定义回调函数,从指令调用它。

.controller('fiveYearCtrl', [ 
    '$scope', 'reports', 
    function ($scope, reports) { 
     this.consoleLog = function (newValue, oldValue) { 
      if (angular.isDefined(newValue)) 
       console.log("I see a data change!"); 
     }; 
    } 
]) 

link: function postLink(scope, element, attrs, ctrl) 
{ 
    scope.lightState = scope.inactiveText; 
    scope.state = { 
     value: false, 
     toggle: function() { 
      this.value = !this.value; 
      scope.lightState = this.value ? scope.activeText : scope.inactiveText; 
      console.log(scope.lightState); 

      //working 
      scope.$watch('lightState', ctrl.consoleLog, true); 
     } 
    }; 
} 
+0

你好,谢谢你的快速反应。 console.log只是我知道事件是否被触发的一种方式。我们的目标是更新当用户点击该按钮控制器的一些数据,所以我只是想打从指令控制器的功能,这将更新数据源? – aghaux

+0

我知道,这仅仅是一个例子,向你展示如何完成。你可以在控制器中创建你喜欢的任何函数,并从指令中调用它。 – Ankh