我有一个 plnkr here我正在使用 controller as syntax
在单选按钮上测试 $scope.$watch。此外,单选按钮嵌入在父 View 容器中。
在'关于我们' 页面中,我有以下 html 代码用于显示两个单选按钮以及当前选择消息:
<div class="row-fluid">
<div class="well">
<p><strong>Make a selection:</strong></p>
<label>Yes</label>
<input type="radio" name="selection" ng-model="aboutView.radioSelection" value="Yes">
<label>No</label>
<input type="radio" name="selection" ng-model="aboutView.radioSelection" value="No">
<p>{{aboutView.message}}</p>
</div>
我在 aboutController.js 中有以下代码:
(function() {
'use strict';
angular.module('layoutApp')
.controller('aboutController', aboutController);
aboutController.$inject = ['$scope'];
function aboutController($scope) {
var vm = this;
vm.radioSelection = "No"; //default selection
vm.message = "Your selection is " + vm.radioSelection;
/**
* **This does not have any response, not working**
$scope.$watch(vm.radioSelection, function(newVal, oldVal) {
vm.message = newVal;
}, true);
*/
}
}())
最后,我的 ui.router 配置中有以下与“关于我们”页面相关的代码块:
.state('home.about', {
url: '/about',
templateUrl: 'about.html',
controller: 'aboutController as aboutView'
})
最佳答案
以下作品:
$scope.$watch(
function() { return vm.radioSelection},
function(newVal, oldVal) {
vm.message = "Your selection is " + newVal;
},
true
);
关于javascript - AngularJS:使用 $scope.$watch 和 Controller 作为语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200161/