繁体   English   中英

将参数从html指令传递给控制器

[英]Pass parameters from html directive to controller

我想将参数从html指令传递给控制器​​示例:

指示:

angular.module('app')
   .directive('helloWorld', function () {
  return {
      replace: false,
      restrict: 'AE',
      templateUrl: "./views/templates/helloWorld.html" 
  }
});

helloWorld.html:

<body ng-app="app" >
<div ng-controller="HelloWorldCtrl">
{{ welcome }}
</div>

hello.html:

<body ng-app="app">
<hello-world/>
</body>

HelloWorldCtrl:

angular.module('app')
.controller('HomeWorldCtrl', function ($scope, ) {

    $scope.welcome = "Welcome"

    };
})

我可以在hello.html中指定参数吗?

<hello-world param="param1"/>

那是传递给控制器​​吗? 因此,在HomeWorldCtrl中,我可以检查参数的值吗? 有没有更好的选择来实现这一目标?

谢谢,

app.directive('helloWorld', function(){
return {
  restrict:'E',
  scope: {
     param: '@'
  },
  template:'<div class="param"><h2>{{param}}</h3></div>'
};
});

// you have options to choose from

//= is two-way binding
//@ simply reads the value (one-way binding)
//& is used to bind functions

<hello-world="someParam"></hello-world>
//    for the scope definition:

scope: {
title: '@helloWorld'
}
The usage in the template will remain the same

<hello-world param="someParam"></hello-world>

如果您不使用隔离范围(范围:{someparam:“”}),则可以在指令模板中使用任何$ scope属性,而无需进行任何更改:

$scope.param = "new param value";
..
return {
  ..
  ,template: "<param>{{param}}</param>" 

谢谢!

指示

   return {
      replace: false,
      restrict: 'AE',
      templateUrl: "./views/templates/PatientSearchEdit.html",
      scope: {
          param: '@'
      }
  }

控制者

console.log($scope.param);

确实记录指定的值。 非常感谢你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM