观察表达并没有从ng-change中获得模型变化

时间:2013-01-08 00:39:33

标签: ruby-on-rails coffeescript angularjs haml

我有以下内容 Rails HAML:

 = select_tag "some-class",
                        options_for_select([['None', '']], ''),
                        { class: 'some-other-class',
                          'ng-model' => 'someModel',
                          'ng-options' => 'option.name for option in someList',
                          'ng-change' => 'updateSelected()'}

角度控制器:

  scope.updateSelected = ->
       #logic for updating model lives here. Model updates successfully by using some values defined within scope. Includes the following:
       scope.someModel = "some_new_value"

Angular Directive:

  SomeClassDirective= ->
       restrict: 'C'

       link: (scope, element, attrs) ->

            monitorFormFields = (newValue, oldValue) ->
                   console.log "this is the inner function call"
                   #logic for setting the inner _destroy field lives here

            scope.$watch 'someModel', monitorFormFields

但是,当选择列表值更改时,'这是内部函数调用'从不打印。(它在指令首次初始化时打印,即在页面加载时打印)。因此我的问题是:为什么$ watch表达式不会触发,我该如何触发?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用此HTML:

<select class="some-class" ng-model="someModel" 
   ng-options="option.name for option in someList"></select>

这是一个指令,会关注someModel的更改:

myApp.directive('someClass', function () {
  return {
    restrict: 'C',
    link: function (scope, element, attrs) {
      var monitorFormFields = function (newValue, oldValue) {
        console.log("this is in the inner function call");
      }
      scope.$watch('someModel', monitorFormFields);
    }
  }
});

控制器:

$scope.someList = [{ name: 'name1' }, { name: 'name2' }];

请注意,您无需调用控制器方法来更新someModel - 由于ng-model属性,Angular会自动为我们执行此操作。因此,该指令只需要监视$ scope属性的更改。

Fiddle


  

我想从元素中获取名称中包含[_destroy]的兄弟,并根据选择框的值将其设置为“0”或“1”。

更具角度的方法是让模型属性控制是否显示“0”或“1”。例如,在您的控制器中:

$scope.destroy1 = "0";
$scope.destroy2 = "0";

在您的HTML中:

<div>{{destroy1}}</div>
<div>{{destroy2}}</div>

在monitorFormFields()中,您可以更改这些范围属性的值,并且视图将自动更新 - 无需“查找”兄弟姐妹或更新.val()ues。