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

Pass parameters from html directive to controller

本文关键字:控制器 指令 参数 html      更新时间:2023-09-26

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

命令:

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

你好世界.html:

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

您好.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);

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