栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在自定义指令中获取评估的属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在自定义指令中获取评估的属性

注意:我会在找到更好的解决方案时更新此答案。 只要它们仍然相关,我也会保留旧的答案以供将来参考。最新最好的答案是第一位的。

更好的答案:

angularjs中的指令功能非常强大,但是要花些时间来了解它们背​​后的进程。

创建指令时,angularjs允许您创建一个 隔离范围 ,并与父范围进行一些绑定。这些绑定由指定的 属性 ,你附加元素在DOM和你如何定义
范围 在属性 指令定义对象

您可以在范围内定义3种类型的绑定选项,并将它们写为与前缀相关的属性。

angular.module("myApp", []).directive("myDirective", function () {    return {        restrict: "A",        scope: { text: "@myText", twoWayBind: "=myTwoWayBind", oneWayBind: "&myOneWayBind"        }    };}).controller("myController", function ($scope) {    $scope.foo = {name: "Umur"};    $scope.bar = "qwe";});

的HTML

<div ng-controller="myController">    <div my-directive my-text="hello {{ bar }}" my-two-way-bind="foo" my-one-way-bind="bar">    </div></div>

在那种情况下,在指令的范围内(无论是在链接函数还是在控制器中),我们可以像下面这样访问这些属性:

in: $scope.textout: "hello qwe"// this would automatically update the changes of value in digest// this is always string as dom attributes values are always stringsin: $scope.twoWayBindout: {name:"Umur"}// this would automatically update the changes of value in digest// changes in this will be reflected in parent scope// in directive's scopein: $scope.twoWayBind.name = "John"//in parent scopein: $scope.foo.nameout: "John"in: $scope.oneWayBind() // notice the function call, this binding is read onlyout: "qwe"// any changes here will not reflect in parent, as this only a getter .

“仍然可以”答案:

由于此答案已被接受,但存在一些问题,因此我将其更新为更好的答案。显然,这

$parse
是一项不位于当前范围属性内的服务,这意味着它仅采用角度表达式而无法达到范围。
{{
}}
表达式在angularjs启动时进行编译,这意味着当我们尝试在指令
postlink
方法中访问它们时,它们已经被编译。(
{{1+1}}
已经
2
在指令中)。

这是您要使用的方式:

var myApp = angular.module('myApp',[]);myApp.directive('myDirective', function ($parse) {    return function (scope, element, attr) {        element.val("value=" + $parse(attr.myDirective)(scope));    };});function MyCtrl($scope) {    $scope.aaa = 3432;}​

<div ng-controller="MyCtrl">    <input my-directive="123">    <input my-directive="1+1">    <input my-directive="'1+1'">    <input my-directive="aaa"></div>​​​​​​​​

您应该在这里注意到的一件事是,如果要设置值字符串,则应将其用引号引起来。(请参阅第3输入)

旧答案:

对于那些可能像我一样被误导的人,我不会删除它,请注意,使用它

$eval
是正确的正确方法,但是
$parse
行为有所不同,在大多数情况下,您可能不需要使用它。

再次使用方法

scope.$eval
。它不仅可以编译角度表达式,还可以访问当前范围的属性。

var myApp = angular.module('myApp',[]);myApp.directive('myDirective', function () {    return function (scope, element, attr) {        element.val("value = "+ scope.$eval(attr.value));    }});function MyCtrl($scope) {}​

你所缺少的是

$eval

在当前范围内执行表达式并返回结果。表达式中的任何异常都会传播(未捕获)。这在评估角度表达式时很有用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号