AngularJS将变量从自定义指令传递给模板

kat*_*thy 3 javascript directive angularjs

我做了一个自定义指令:

js部分:

angular.module("myDirectives", []).directive("ngShowbox", function(){
  return {
    restrict: "E",
    scope: {
      title: "="
    },
    template: "<a href='#' ng-click='show($event)'>{{title}}</a>",
    controller: function($scope, $element){
      $scope.show = function(event){
        // do something...
      }      
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML部分:

<ng-showbox title="whatToPutHere??"></ng-showbox>
Run Code Online (Sandbox Code Playgroud)

我想从title属性传递一些文本,然后我的模板将显示文本.我该怎么做?

非常感谢你 :)

squ*_*oid 6

在指令范围内使用@: -

scope: {
      title: "@"
    },
Run Code Online (Sandbox Code Playgroud)

Plunker为你:)

  • 只是注意,如果你将title的值赋给控制器范围值,那么你需要使用`title:"="`.:),如果你只需要字符串值,而不是`title`中的范围值你可以使用``title:"@"`` (2认同)
  • 完全正确的:)"="将为您提供双向绑定功能,而"@"只是将字符串绑定到范围. (2认同)