更新Angular Directive的值时出现问题's模型,同时从表单的监视进行更新

Issue while updating value of Angular Directive's model while updating from watch of form

本文关键字:更新 模型 监视 表单 Directive Angular 问题      更新时间:2023-09-26

Am试图通过在表单模型的$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);
});

}]);

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

您正在嵌套的不同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被激发时更新的属性。

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