簡體   English   中英

在angular指令上停止雙向數據綁定

[英]Stop two way data binding on angular directive

我想將信息傳遞給這樣的指令:

<ui-message data="{{app}}"></ui-message>

我在控制器中的以下位置:

app.controller("testCtrl", function($scope) {
  $scope.app = "Hello World!"
})

而我的指令:

app.directive("uiMessage", function() {
  return {
    template: "<h1>{{message}}</h1>",
    scope: {
      message: "@data"
    }
  }
})

效果很好,但是如果將app綁定到模型,它將更新指令中的內容:

<input ng-model="app"> //typing here changes the content inside ui-message
<ui-message data="{{app}}"></ui-message>

如何防止這種情況發生?

與“ @”的單向綁定與您所想的方向相反-它防止指令中的更改復制回父作用域,而不是父范圍中的更改不會影響指令。 您可能想要做的是使用angular.copy復制數據,然后將該副本傳遞給指令。

app.controller("testCtrl", function($scope) {
  $scope.app = "Hello World!"
  $scope.appCopy = angular.copy($scope.app);
})

那時,模板中不需要單向數據綁定:

<ui-message data="appCopy"></ui-message>

還是你的指令

app.directive("uiMessage", function() {
  return {
    template: "<h1>{{message}}</h1>",
    scope: {
      message: "=data"
    }
  }
})

您可以將一次性綁定表達式::

 function uiMessage() { return { template: "<h1>{{::msg}}</h1>", scope: { msg: "=" } } } function myController($scope) { $scope.message = "one way"; } angular.module('myApp', []); angular .module('myApp') .controller('myController', myController) .directive('uiMessage', uiMessage); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="myController"> <input type="text" ng-model="message" /> <ui-message msg="message"></ui-message> </div> </div> 

如果這確實是一次性的事情,並且您不需要該變量,則可以使用ng-transclude而不是創建范圍:

 function uiMessage() { return { transclude: true, template: "<h1 ng-transclude></h1>" } } function myController($scope) { $scope.message = "one way"; } angular.module('myApp', []); angular .module('myApp') .controller('myController', myController) .directive('uiMessage', uiMessage); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="myController"> <input type="text" ng-model="message" /> <ui-message>{{::message}}</ui-message> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM