以下是运行良好的代码,没有任何问题。我唯一无法得到的是 -
每当按钮按下时,如何控制台 console.log("CHECK ",vm.testvar);
。
工作 Plnkr - http://plnkr.co/edit/BGdGgGaDXlKiZq2aaN00?p=preview
script.js -
var myApp = angular.module('myApp', []);
myApp.controller('mainCtrl', function($scope){
$scope.test = 'my test string from controller';
$scope.clicked = function() {
$scope.test = 'New - ' + Date.now();
};
})
myApp.directive('mydir', function(){
return {
restrict: 'E',
scope: {
testvar: '='
},
template: '<h1>Test Directive - {{vm.testvar}}</h1>',
controllerAs: 'vm',
replace: true,
bindToController: true,
controller: function () {
var vm = this;
console.log("CHECK ",vm.testvar);
}
};
})
最佳答案
有多种方法可以解决这个问题,但最快的方法,也可能是最 Angular 1.* 方法是使用 $scope.$watch
方法:
controller: function ($scope) {
var vm = this;
$scope.$watch( 'vm.testvar', function(newValue){
console.log( 'cHanged', newValue)
})
console.log("CHECK ",vm.testvar);
}
关于javascript - 如何在 AngularJS 中控制台从 Controller 到指令 Controller 的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788488/