javascript - AngularJS:使用 $scope.$watch 和 Controller 作为语法

标签 javascript angularjs controller scope angular-ui-router

我有一个 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
);

Plunkr

关于javascript - AngularJS:使用 $scope.$watch 和 Controller 作为语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200161/

相关文章:

javascript - 在 Angular 中访问嵌套的json并在php中显示

javascript - 获取字符串中的特定键值

javascript - AngularJS:动态 base64 编码图像的 ng 类作为背景图像

json - Spring 中的非必需 JSON 属性(Jackson 映射)

javascript - Angular Controller 未加载

javascript - 在React中播放状态相关的音频文件

javascript - 如何在禁用的 asp.net 下拉列表中添加警报?

javascript - 我无法在 FireFox 中的 <area> 标签上触发 jQuery 悬停事件

javascript - 如果 dom 中存在内部文本,如何接收 true false

ruby-on-rails - Rspec 测试不会通过使用 assigns()