从角度指令调用控制器功能

时间:2013-11-22 12:03:06

标签: javascript angularjs angularjs-directive angularjs-scope

如何在控制器中定义的指令内调用angular函数?

var app = angular.module('myApp', ['ngResource']);

app.directive('hello', function () {
    return {
        scope: {
            myObj: '=hello'
        },
        template: '<button  class="btn btn-primary" ng-click="dirFunction()">Click</button>',
        link: function (scope) {
            scope.dirFunction = function () {
                scope.count++;
                console.log('I am dirFunction');
            };
            var countChange = function (someVar) {
               console.log('I am countChange');
              // scope.changeCount(someVar); // call  changeCount() defined in controller
            };

           // scope.$watch('myObj', hello);
            scope.$watch('count', countChange);
        }
    }
});


function MyCtrl($scope) {
    $scope.message = 'Can I do it?';
    $scope.myObj = {data:'I need this data object',count:1};

    $scope.changeCount = function(someVar) {
        console.log("I am changeCount from controller,I have someVar in hand");
    }

}

我需要在指令中调用注释的scope.changeCount(someVar);

参见HTML,

<div ng-app="myApp">
  <div class="container" ng-controller="MyCtrl">
        <div class="row">
          {{message}}
          <div hello="myObj"></div>  
        </div><!--/row-->
  </div>
</div>

Fiddle here.

1 个答案:

答案 0 :(得分:3)

使用隔离范围从指令内部调用父作用域上的控制器函数时使用&

HTML

<div hello="myObj" change-count="changeCount(someVar)"></div> 

指令

app.directive('hello', function () {
    return {
        scope: {
            myObj: '=hello',
            changeCount:"&changeCount"
        },
        template: '<button class="..." ng-click="dirFunction()">Click</button>',
        link: function (scope) {
            scope.dirFunction = function () {
                scope.myObj.count++;
                console.log('I am dirFunction '+scope.myObj.count);
            };
            var countChange = function (someVar) {
                console.log('I am countChange '+someVar);
                scope.changeCount({'someVar':someVar});
            };             
            scope.$watch('myObj.count', function(newValue){
                countChange(newValue)
            });
        }
    }
});

Fiddle