【问题标题】:Angular JS $interpolate queryAngular JS $interpolate 查询
【发布时间】:2014-11-08 15:40:22
【问题描述】:

我是 Angular JS 的新手,试图理解如下编写的指令功能

function mydirective($interpolate, $compile) {
return {
    restrict: 'E',
    scope: {
        mycontent: '=',
        myurls: '=',
        mydata: '@'
    },
    replace: true,
    template: '<div ng-bind-html="html"></div>',
    link: function ($scope, element, attrs) {
        $scope.$watch('mycontent', function (value) {
            var html = $interpolate(value)($scope);

            element.html(html);

            $compile(element.contents())($scope);
        });
 } 
}
}  

我无法从上面理解以下内容。

1) 这个 $interpolate(value)($scope) 做什么?第二个参数 $scope 是什么。

2) 这个 $compile 函数在做什么?

3) 模板中的 div ng-bind-html="html" 有什么作用?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

这个 $interpolate(value)($scope) 有什么作用?

获取value变量的字面值

第二个参数 $scope 是什么。

它为数据绑定提供上下文

it('should interpolate with undefined context', inject(
   function($interpolate) 
     {
     expect($interpolate("Hello, world!{{bloop}}")()).toBe("Hello, world!")
     }
  ));

这个 $compile 函数在做什么?

它将字符串转换为 Angular 标记

div ng-bind-html="html" in template 有什么作用?

它编译 $scope.html 中的 HTML 字符串并将其添加到标记中

参考文献

【讨论】:

  • 对于初学者来说,使用“literal”可能真的很困惑。为什么不直接说:“当 scope.fruits = 'bananas apples pears' 时,它会将诸如 '{{fruits}}' 之类的字符串评估为 'banana apples pears'”。
  • @WilliamNeely 我考虑过这个问题,但决定不使用evaluates 或formats 这两个词,因为这假定了编程背景。一张图值一千字,所以我加了一张。
猜你喜欢
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 2019-06-08
  • 2012-09-05
  • 2021-02-09
  • 2017-11-25
相关资源
最近更新 更多