AngularJS指令在隔离范围中的两种方式绑定不会在父范围中反映

我试图将范围数组元素传递给指令并在指令中更改该元素的值,但是当我打印范围元素的值时,在指令范围内进行的更改在父范围中不受影响。我创建了隔离范围,并在范围内使用<div ng-app="dr" ng-controller="testCtrl"> <test word="word" ng-repeat="word in chat.words"></test> <button ng-click="find();"> click </button> </div> 提供了两种方式的绑定,但它没有对父范围进行任何更改。 附加代码

Index.html

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部分

'='

我的大部分搜索都返回将use App\Customer; $customer_fullname = Customer::select(DB::raw("concat('first_name','middle_name') AS Full_Name"))->get(); 放入指令范围将解决此问题,但是这样做并不走运。任何人都可以指出问题所在,以及如何在父范围中反映该值。

wzx1123 回答:AngularJS指令在隔离范围中的两种方式绑定不会在父范围中反映

您将字符串传递给指令,并且该字符串不再与您的数组无关,因此未对其进行引用 我想你必须正确地改变数组

类似以下的方法应该起作用:

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>
,

可以通过使用单向(<)绑定来提高指令的效率:

app.directive('test',scope: {
            ̶w̶o̶r̶d̶:̶ ̶'̶=̶'̶
            word: '<'
        },attrs) {             
        }
    }
});

单向(<)绑定还具有与$onChanges life-cyle hook一起使用的优势。

本文链接:https://www.f2er.com/3080937.html

大家都在问