[英]AngularJS: use $scope.$watch with controller as syntax
我在這里有一個 plnkr,我正在使用controller as syntax
在單選按鈕上測試$scope.$watch 。 此外,單選按鈕嵌入在父視圖容器中。
在“關於我們”頁面中,我有以下 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
);
你可以試試這個,使用你在控制器 As 中設置的 'aboutView' 而不是 vm。
$scope.$watch('aboutView.radioSelection', function(newVal, oldVal) {
vm.message = "Your selection is " + newVal;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.