AngularJS:使用$ scope。$ watch with controller作为语法

时间:2015-03-22 21:38:42

标签: javascript angularjs controller scope angular-ui-router

我有一个plnkr here我正在使用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配置中的以下代码块与about us页面相关:

.state('home.about', {
      url: '/about',
      templateUrl: 'about.html',
      controller: 'aboutController as aboutView'
    })

2 个答案:

答案 0 :(得分:12)

以下作品:

  $scope.$watch(function() { return vm.radioSelection}, function(newVal,     oldVal) {
  vm.message = "Your selection is " + newVal;
}, true);

Plunkr

答案 1 :(得分:0)

你可以尝试这个,使用&#39; aboutView&#39;在控制器中设置为As而不是vm。

$scope.$watch('aboutView.radioSelection', function(newVal,     oldVal) {
    vm.message = "Your selection is " + newVal;
});