Angular add watch to directive的链接功能

时间:2016-05-05 15:06:57

标签: angularjs

我正在尝试跟踪指令中的更改,以及“current_step'变量;

我的指示:

function wizardStepsCircle(logger) {
        var directive = {
            bindToController: true,
            controller: WizardStepsCircleController,
            controllerAs: 'vm',
            templateUrl: 'wizard-steps-circle.html',
            restrict: 'E',
            scope: {
                current_step: '@'
            },
            link: link
        };
        return directive;

        function link(scope, element, attrs) {
            attrs.$observe('current_step', function (newvalue) {
                logger.info('current_step is:', newvalue);
           });           
        }
    }

指令控制器:

function WizardStepsCircleController() {
        var vm = this;      

        activate();

        function activate() {
            vm.c_step = current_step;
        }
    }

指令的HTML:

 <wizard-steps-circle current_step="{{vm.WzrdCtrls.c_step}}"></wizard-steps-circle>
  1. 如何访问&#39; current_step&#39;来自控制器?
  2. &#39; vm.WzrdCtrls.c_step&#39;正在改变但是观察不会被解雇。我做错了什么?
  3. 感谢。

2 个答案:

答案 0 :(得分:1)

你应该改变:

 attrs.$observe('current_step', function (newvalue) {
            logger.info('current_step is:', newvalue);
       }); 

为:

 attrs.$observe('currentStep', function (newvalue) {
            logger.info('current_step is:', newvalue);
       }); 

阅读规范化部分中的here,了解有关此内容的更多信息

答案 1 :(得分:0)

检查这是否是您想要的

angular.module('app',[]).controller('ctrl',function($scope,$http){
var vm = this;
$scope.current_step = 10;

}).directive('wizardStepsCircle',wizardStepsCircle);
function wizardStepsCircle() {
        var directive = {
            bindToController: true,
            controller: WizardStepsCircleController,
            controllerAs: 'vm',

            restrict: 'E',
            scope: {
                current_step: '@cStep'
            },
            link: link
        };
        return directive;

        function link(scope, element, attrs) {
          console.log(scope,element);
            attrs.$observe('cStep', function (newvalue) {
                console.log('cStep:', newvalue);
           });      
          scope.$watch('current_step', function (newvalue) {
                console.log('current_step:', newvalue);
           }); 
        }
    }

function WizardStepsCircleController($scope) {
        var vm = this;      
     console.log("CSCSCS"+$scope.current_step,$scope);
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="current_step">
 <wizard-steps-circle c_step="{{current_step}}"></wizard-steps-circle>
</div>