【问题标题】:AngularJS Directive two way binding in isolated scope not reflecting in parent scopeAngularJS指令在隔离范围内的两种方式绑定不反映在父范围内
【发布时间】:2019-11-18 12:56:50
【问题描述】:

我正在尝试将作用域数组元素传递给指令并更改指令内该元素的值,但是当我打印作用域元素的值时,在指令内所做的更改在父作用域中不受影响。我创建了隔离范围并在范围内使用'=' 提供了两种方式绑定,但它没有对父范围进行任何更改。 附上代码

Index.html

<div ng-app="dr" ng-controller="testCtrl">
    <test word="word" ng-repeat="word in chat.words"></test> 
    <button ng-click="find();">
    click
    </button>
</div>

Javascript 部分

var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
    $scope.chat= {words: [
      'first', 'second', 'third'
    ]};

    $scope.find = function(){
    alert(JSON.stringify($scope.chat, null, 4));
    }
});
app.directive('test', function() {
    return {
        restrict: 'EA',
        scope: {
            word: '='
        },
        template: "<input type='text' ng-model='word' />",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

我的大部分搜索都返回将'=' 放在指令范围内将解决问题,但没有运气。任何人都可以指出问题所在,以及如何在父范围内反映价值。

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    您将一个字符串传递给您的指令,并且该字符串未被引用,因为它不再与您的数组相关 我想你必须正确地改变你的数组

    类似下面的东西应该可以工作:

    var app = angular.module('dr', []);
    app.controller("testCtrl", function($scope) {
        $scope.word = 'test';
        $scope.chat= {words: [
          {'name':'first'}, {'name': 'second'}, {'name' : 'third'}
        ]};
    
        $scope.find = function(){
        alert(JSON.stringify($scope.chat, null, 4));
        }
    });
    app.directive('test', function() {
        return {
            restrict: 'EA',
            scope: {
                word: '='
            },
            template: "<input type='text' ng-model='word.name' />",
            replace: true,        
            link: function(scope, elm, attrs) {             
            }
        }
    });
    
    <div ng-app="dr" ng-controller="testCtrl">
        <pre>{{chat.words}}</pre>
        <test word="word" ng-repeat="word in chat.words"></test> 
        <button ng-click="find();">
            click
        </button>
    </div>
    

    【讨论】:

      【解决方案2】:

      使用单向 (&lt;) 绑定可以使指令更高效:

      app.directive('test', function() {
          return {
              restrict: 'EA',
              scope: {
                  ̶w̶o̶r̶d̶:̶ ̶'̶=̶'̶
                  word: '<'
              },
              template: "<input type='text' ng-model='word.name' />",
              replace: true,        
              link: function(scope, elm, attrs) {             
              }
          }
      });
      

      单向 (&lt;) 绑定具有与$onChanges life-cyle hook 一起使用的额外优势。

      【讨论】:

        猜你喜欢
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多