在指令中使用链接和模板属性

时间:2018-12-31 07:46:08

标签: javascript angularjs

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。

1 个答案:

答案 0 :(得分:0)

只需使用'+'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>