首页 > 解决方案 > 在指令中使用链接和模板属性

问题描述

Wants to use the link function of the directive. Such that it should display a name and on click should change it to the new given name. but there is some error in my template property. w
Where do i get wrong?

JS code-
var app=angular.module("app",[]);

app.controller("myController",function($scope){

});

app.directive("myDirective",function(){
    return{
        restrict:"EA",

        link: function($scope,element,attr){
         $scope.name="Hello World";
         $scope.changeName=function(newName){
            $scope.name=newName;
         }
        },
        template: '<span ng-click="changeName('Hi!')">current name:{{name}}</span>'

    };
});

HTML code-
<hmtl>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
<script src="example4.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="myController">
        <div my-directive ></div>
    </div>
</body>
</hmtl>

首先,我将指令限制为“EA”。然后为范围提供一个名称,并为范围提供一个“changeName”函数。然后提供了一个模板以在单击时将初始化名称更改为 newName。

标签: javascriptangularjs

解决方案


只需使用 '+'hi'+'

        <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="myController">
 <w3-test-directive></w3-test-directive> </div>

<script>
var app = angular.module("myApp", []);
app.controller("myController",function($scope){

});

app.directive("w3TestDirective",function(){
    return{
        restrict:"EA",

    link: function($scope,element,attr){
     $scope.name="Hello World";
     $scope.changeName=function(newName){
        $scope.name=newName;
     }
    },
    template: '<span ng-click="changeName('+'hi'+')">current name:{{name}}</span>'

    };
});
</script>

</body>
</html>

推荐阅读