javascript - 如何在angularjs指令中使用动态模板

标签 javascript angularjs

我想创建一个动态指令。在此指令中定义一个具有输入元素的模板。事实上这个元素 ng-model 必须是动态的,并且在 Controller 中使用 $scope.name

app.directive('helloWorld', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
              name: '@',
              path:'@',
        },
        template: '<input\
             type="text"\
             name="{{name}}"\
             ng-model="{{name}}"\
              />\,
        link: function(scope, elem, attrs) {

        },
        controller:{
          $scope.$watch($scope.name, function (newValue, oldValue) {
            }
        }
    });

最佳答案

A working JSFiddle

代码

var app = angular.module('app',[])
app.directive('helloWorld', function() {
   return {
   restrict: 'E',
scope: {
     name: '@',
     path:'@',
  },

   template: '<input type="text" name="{{name}}" ng-model="name"/> {{name}}',
 controller: function($scope) {
   $scope.name = "initial value";
   $scope.$watch('name', function (newValue, oldValue) {
       console.log("newValue: ",newValue);
   })
 }       

} });

关于javascript - 如何在angularjs指令中使用动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31581975/

相关文章:

javascript - 如何在 jquery 验证插件中添加自定义错误替换消息?

angularjs - Node.js 使用什么模板引擎

javascript - HTML5 pushState Clash w/Angular UI-Router URL 路由

javascript - 为什么我的代码在 underscore.js 下可以工作,但在我使用 Ramda.js 时却不行?

javascript - 在 Angular JS 日期选择器中以年份格式预选择年份

javascript - 如何在 Angularjs 指令中渲染 html?

javascript - 暂时禁用 AngularJS 中的表单验证

javascript - 如何阅读谷歌浏览器扩展中的剪贴板文本

javascript - jQuery 的 html() 会删除附加到被替换元素的所有数据吗?

javascript - Websockets - 服务器端要求(Windows 服务器,而不是 Apache)