gpt4 book ai didi

javascript - 停止对 Angular Directive(指令)的双向数据绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 09:44:51 25 4
gpt4 key购买 nike

我想像这样将信息传递给指令:

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

在我的 Controller 中我有以下内容:

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

还有我的指令:

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

这很好用,除了如果 app 绑定(bind)到一个模型,它会更新指令中的内容:

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

如何防止这种情况发生?

最佳答案

您可以使用 one time binding expression使用 ::

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>

关于javascript - 停止对 Angular Directive(指令)的双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39278854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com