Javascript 如何从外向内获取指令中的值?
这是你的电话号码。Javascript 如何从外向内获取指令中的值?,javascript,angularjs,angular-directive,Javascript,Angularjs,Angular Directive,这是你的电话号码。 HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> link1 is <
HTML:
<body ng-app="app">
<h1>selectable</h1>
<selectable text="link1" status="true"></selectable>
<selectable text="link2" status="false"></selectable>
<p>
link1 is <!--status of link1, true or false-->
</p>
<p>
link2 is <!--status of link2, true or false-->
</p>
</body>
模板:
<span class='myLink' ng-class='{"active": status, "": !status}'>
{{text}}
{{status}}
</span>
{{text}}
{{status}}
如何获取link1和link2的状态,然后显示它们?
谢谢 您需要将该值放在某个范围变量中,并将其传递给指令
属性
,因为您已经在使用=
(双向绑定)angular将显示绑定的魔力。如果传递给隔离指令的值将发生更改,则它将更改传递的基础范围值,反之亦然
标记
<body ng-app="app">
<h1>selectable</h1>
<selectable text="link1" status="link1Bool"></selectable>
<selectable text="link2" status="link2Bool"></selectable>
<p>
link1 is {{link1Bool}}
</p>
<p>
link2 is {{link2Bool}}
</p>
</body>
可选的
link1是{{link1Bool}}
link2是{{link2Bool}}
使用ng控制器
指令
<body ng-app="app" ng-controller="MainCtrl">
将这两个变量绑定到指令范围的状态
变量
<selectable text="link1" status="link_1_status"></selectable>
<selectable text="link2" status="link_2_status"></selectable>
这是你的电话号码
为什么
如果使用like
,则将true
分配给指令作用域status
变量,单击该变量将切换该值,但您无法访问该值,因为您没有对该值的任何引用(您只需传递一个原始值,而没有引用或标识),因此,您需要一个引用来访问该变量,这就是为什么我们需要一些link\u 1\u status
和link\u 2\u status
来访问该属性。以下是示例
我认为正确的方法是拥有一个控制器,使用它在表单之间共享数据,并添加一些逻辑来处理数据
<body ng-app="app" ng-controller="ctrl">
<h1>selectable</h1>
<selectable text="link1" status="firstStatus"></selectable>
<selectable text="link2" status="secondStatus"></selectable>
<p>
link1 is {{firstStatus}}
</p>
<p>
link2 is {{secondStatus}}
</p>
</body>
您可以简单地使用ng show如何获取link1和link2的状态,然后显示它们。。将视图中的状态发送到隔离作用域指令的状态为true或false,从何处获取,请解释或详细说明你想要实现的目标
<selectable text="link1" status="link_1_status"></selectable>
<selectable text="link2" status="link_2_status"></selectable>
<p>
link1 is {{link1Bool}}
</p>
<p>
link2 is {{link2Bool}}
</p>
<body ng-app="app" ng-init="link_1_status = true; link_2_status = false">
....
<selectable text="link1" status="link_1_status"></selectable>
<selectable text="link2" status="link_2_status"></selectable>
....
</body>
<body ng-app="app" ng-controller="ctrl">
<h1>selectable</h1>
<selectable text="link1" status="firstStatus"></selectable>
<selectable text="link2" status="secondStatus"></selectable>
<p>
link1 is {{firstStatus}}
</p>
<p>
link2 is {{secondStatus}}
</p>
</body>
.controller("ctrl", function($scope){
$scope.firstStatus = true;
$scope.secondStatus = false;
})