当用户切换按钮时,我在控制器中实现了一个手表。我在指令中有一块手表,它正在工作,例如它检测到范围变量有变化,但如果我在控制器内有监视器,则它不会检测到
<button toggle-button active-text="Yes" inactive-text="No" ng-model="light.state">Show millions</button><br>
&#13;
这是代码:
'use strict';
angular.module('fiveYearOverview', ['fiveYearOverviewServices', 'fiveYearOverviewDirectives'])
.controller('fiveYearCtrl', [
'$scope', 'reports',
function ($scope, reports) {
//not working
$scope.$watch('lightState', function (newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
}, true);
}
])
.directive('toggleButton', function () {
return {
require: 'ngModel',
scope: {
activeText: '@activeText',
inactiveText: '@inactiveText',
lightState: '=ngModel'
},
replace: true,
transclude: true,
template: '<div>' +
'<span ng-transclude></span> ' +
'<button class="btn" ng-class="{\'btn-primary\': state.value}" ng-click="state.toggle()">{{activeText}}</button>' +
'<button class="btn" ng-class="{\'btn-primary\': !state.value}" ng-click="state.toggle()">{{inactiveText}}</button>' +
'</div>',
link: function postLink(scope) {
scope.lightState = scope.inactiveText;
scope.state = {
value: false,
toggle: function () {
this.value = !this.value;
scope.lightState = this.value ? scope.activeText : scope.inactiveText;
console.log(scope.lightState);
//working
scope.$watch('lightState', function (newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
}, true);
}
};
}
}
});
&#13;
我做错了什么?
答案 0 :(得分:2)
通过在指令中定义范围,您将为其创建隔离范围。这就是你无法从控制器访问其成员的原因。
答案 1 :(得分:0)
lightState
在fiveYearCtrl
以下的范围内宣布,使其无法按照here所述进行宣传。
另一种解决方案可能是在fiveYearCtrl
中定义回调函数并从指令中调用它。
.controller('fiveYearCtrl', [
'$scope', 'reports',
function ($scope, reports) {
this.consoleLog = function (newValue, oldValue) {
if (angular.isDefined(newValue))
console.log("I see a data change!");
};
}
])
link: function postLink(scope, element, attrs, ctrl)
{
scope.lightState = scope.inactiveText;
scope.state = {
value: false,
toggle: function () {
this.value = !this.value;
scope.lightState = this.value ? scope.activeText : scope.inactiveText;
console.log(scope.lightState);
//working
scope.$watch('lightState', ctrl.consoleLog, true);
}
};
}