1
我执行在控制器的手表,当用户切换按钮在未检测指令的变化。我有一个手表内的指令,并正在工作,例如它检测到的范围变量的变化,但如果我有在控制器内的手表不检测
<button toggle-button active-text="Yes" inactive-text="No" ng-model="light.state">Show millions</button><br>
这里是代码:
'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);
}
};
}
}
});
这是什么我做错了?
你好,谢谢你的快速反应。 console.log只是我知道事件是否被触发的一种方式。我们的目标是更新当用户点击该按钮控制器的一些数据,所以我只是想打从指令控制器的功能,这将更新数据源? – aghaux
我知道,这仅仅是一个例子,向你展示如何完成。你可以在控制器中创建你喜欢的任何函数,并从指令中调用它。 – Ankh