【发布时间】:2021-04-06 06:43:01
【问题描述】:
我有一个指令需要时不时地做一些事情,假设它必须计算一些东西。 如果我使用 $scope 的基本语法来绑定 count 函数,它就可以正常工作。但是当我们以语法形式切换到控制器时,它不会绑定函数。 这是一个工作的 plunker:https://plnkr.co/edit/C2wVaeOm63SLnXBG?open=lib%2Fscript.js&deferRun=1&preview
JS
angular
.module('plunker', [])
.controller('MainCtrl', function ($scope) {
var vm = this;
vm.name = 'Plunker';
setInterval(function () {
$scope.count();
}, 1000);
setInterval(function () {
$scope.count2();
}, 1000);
setInterval(function () {
$scope.count3();
}, 1000);
})
.directive('test', function () {
return {
scope: {
count: '=',
},
controller: function ($scope) {
$scope.i = 0;
$scope.count = function () {
$scope.i++;
console.log($scope.i);
};
},
};
})
//with bindToController
.directive('test2', function () {
return {
scope: {
count: '=',
},
bindToController: true,
controller: function ($scope) {
var vm = this;
vm.i = 0;
vm.count = function () {
vm.i++;
console.log(vm.i);
};
},
};
})
//with bindToController - the new way
.directive('test3', function () {
return {
scope: true,
bindToController: {
count: '=',
},
controller: function ($scope) {
var vm = this;
vm.i = 0;
vm.count = function () {
vm.i++;
console.log(vm.i);
};
},
};
});
HTML
<body ng-app="plunker" ng-cloak>
<div ng-controller="MainCtrl as vm">
<h1>Hello {{vm.name}}</h1>
<test count="count"></test>
<test2 count="count2"></test>
<test3 count="count3"></test>
</div>
</body>
【问题讨论】:
标签: angularjs angularjs-directive parameter-passing angularjs-controlleras