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

Had*_*i J 5 javascript angularjs

我想创建一个动态的指令.在此指令中,定义具有input元素的模板.实际上,这个元素ng-model必须是动态的,并且$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) {
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

Raz*_* B. 0

首先,您的指令语法是错误的,这是正确的:

app.directive('helloWorld', function() {
   return {
     restrict: 'E',
      scope: {
        name: '@',
        path:'@',
      },
     template: '<input type="text" name="{{name}}" ng-model="name">',
     link: function(scope, elem, attrs) {
  
     },
     controller: function($scope) {
       $scope.name = 'asd';
       $scope.$watch('name', function (newValue, oldValue) {

       })
     }
  }
});
Run Code Online (Sandbox Code Playgroud)

其次,如果您希望拥有动态model,则应该scope: {name: '='}按原样使用@一次性绑定

编辑

name="name模板中更改为name="{{name}}"

这是一个演示