【问题标题】:Issue while updating value of Angular Directive's model while updating from watch of form从表单的手表更新时更新Angular Directive模型的值时出现问题
【发布时间】:2015-11-24 17:11:22
【问题描述】:

我正在尝试通过在表单模型的 $watch 期间更新的模型来更新角度指令的绑定。尽管模型的值在表单监视的控制器范围内更新,但它不会在指令渲染中更新。有什么想法我可能会出错吗?

<html ng-app="App">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
  <body>
<div ng-controller="ctrl">
<test-directive  my-string="myString"></test-directive>
<form name="myForm" ng-controller="ctrl" >
  userType: <input name="input" ng-model="userType">

</form>

<input type="text" name="input" ng-model="myModel" required />
{{testString}}
</div>


  </body>
</html>

这是 Angular 设置。

var app = angular.module('App', []);

app.directive('testDirective', function ($parse) {
    return{
      restrict: 'E',
    scope:{myString:"=myString"},
      link: function(scope,element,attributes){ 
      var test=[];

      },
      template:' Updated::{{myString}}',

    }
});

app.controller('ctrl',['$scope','$timeout',function($scope,$timeout) {

 $scope.myString='12345';


$scope.$watch('myForm', function(myForm,oldvalue) {
  debugger;
    if(myForm) { 


       $scope.myString='new String';




    }
    else {
        console.log('Form is Undefined');
    }  
});

$scope.$watch('myModel',function(newValue,oldValue){
  console.log(newValue);
});


}]);

基本上,当我的表单被加载并通过控制器访问时,我需要更改指令中的一些数据。

【问题讨论】:

  • 请不要包含您的代码图片,只需包含您的代码即可。 Stack Overflow 有非常好的代码格式。在此处包含相关详细信息会使您的问题更容易回答,并且对遇到相同问题的人更有帮助。
  • 嘿@SunilD.,已更新格式。

标签: javascript angularjs angularjs-directive


【解决方案1】:

您在嵌套的不同 DOM 元素上两次实例化您的控制器。

<!-- Creates a new scope -->
<div ng-controller="ctrl">

<!-- Is pointing to the parent scope -->
<test-directive  my-string="myString"></test-directive>

<!-- Creates a a new nested scope -->
<form name="myForm" ng-controller="ctrl" >
  userType: <input name="input" ng-model="userType">

</form>

这意味着子作用域将获得它自己的属性myString,这是在$watch 被触发时更新的属性。

但是,您的自定义指令指向父属性,因此不会反映更改。

【讨论】:

  • 我的表单元素上的那个重复的 ng-controller 是我在 plunkr 工作时跳过的东西。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 2020-08-13
  • 2021-07-16
  • 2021-04-19
  • 2020-02-24
  • 1970-01-01
  • 2018-10-19
相关资源
最近更新 更多