0

我有以下 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"

角度指令:

  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

However, when the Select List value is changed, 'this is the inner function call' never prints.(it does print when the directive first initializes, ie at page load). 因此,我的问题是:为什么 $watch 表达式没有触发,我如何让它触发?

谢谢!

4

1 回答 1

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——Angular 会自动为我们执行此操作,因为该ng-model属性。因此,该指令只需要 $watch 以查看对该 $scope 属性的更改。

小提琴


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

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

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

在您的 HTML 中:

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

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

于 2013-01-08T18:57:39.570 回答