gpt4 book ai didi

javascript - Thinkster 示例 : Passing data from model into directive

转载 作者:行者123 更新时间:2023-11-27 23:23:06 24 4
gpt4 key购买 nike

我对 Thinkster 示例中的一个部分有疑问。我认为我的缺乏理解源于 JavaScript 知识较弱,并且不了解 AngularJS 的一些基础知识。自 12 月以来,我一直在自学,学习 JavaScript 的基础知识,现在又学习 Angular。如果您能解释一下(就像我 5 岁一样),我将不胜感激! Thinkster Page

App.js

app.controller("ChoreCtrl", function($scope){
$scope.logChore = function(chore){
alert(chore + " is done!");
};
});

app.directive("kid", function() {
return {
restrict: "E",
scope: {
done: "&"
},
template: '<input type="text" ng-model="chore">' +
//This is the part I'm slightly confused about

'{{chore}}' +
'<div class="button" ng-click="done({chore: chore})">I\'m done</div>'
};
});

HTML

    <div ng-app="choreApp">
<div ng-controller="ChoreCtrl">
<kid done="logChore(chore)"></kid>
</div>
</div>

{chore:chore} 是如何工作的? Thinkster 声明如下:

The {chore:chore} syntax maps the chore from the model we made in the <input> to be passed to the logChore function when we said 'done="logChore(chore)"' (in the kid directive)

我的想法是:

  1. 点击调用“done”,后者根据 HTML 属性调用“logChore(chore)”
  2. 我猜App.js中的“{chore:chore}”被传递到logChore中,所以在某种意义上它是logChore(chore:chore)?

为什么我不能只使用ng-click=(done(chore)){chore:chore} 到底发生了什么?很明显我不知道发生了什么哈哈。

非常感谢大家!

最佳答案

这是因为 & 运算符,请参见此处:https://docs.angularjs.org/api/ng/service/ $compile#-scope-

它说:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name.

基本上,它访问父作用域的 chore 属性,否则我们将处于指令的隔离作用域中,而该作用域没有 chore 属性。

此外,请在此处查看他的解释:https://thinkster.io/egghead/isolate-scope-am

看看这段代码是否澄清了一点 - 我修改了属性名称,现在我们有了 innerChoreouterChoreparam避免名称混淆:

var app = angular.module('choreApp', []);

app.controller("ChoreCtrl", function($scope){
$scope.logChore = function(param){
alert(param + " is done!");
};
});

app.directive("kid", function() {
return {
restrict: "E",
scope: {
done: "&"
},
template: '<input type="text" ng-model="innerChore">' +
'{{innerChore}}' +
'<div class="button" ng-click="done({outerChore: innerChore})">I\'m done</div>'
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<div ng-app="choreApp">
<div ng-controller="ChoreCtrl">
<kid done="logChore(outerChore)"></kid>
</div>
</div>

注意{outerChore:innerChore}中的关系。

关于javascript - Thinkster 示例 : Passing data from model into directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213555/

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