簡體   English   中英

從角度指令調用控制器功能

[英]Call controller function from angular directive

如何在控制器中定義的指令內部調用角度函數?

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>

在這里擺弄。

在使用隔離范圍從指令內部調用父范圍內的控制器函數時,請使用&

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

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM