簡體   English   中英

AngularJS:使用 $scope.$watch 和控制器作為語法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM